from sys import exit
N,K = [int(n) for n in input().split()]
# N = int(input())
# a = [int(input()) for _ in range(N)]
S = str(input())
L = len(S)
lis = []
if(S[0] == "0"):#偶数Indexがブリッジ
    lis.append(0)
tmp = S[0]

for i in range(1,L):
    if(S[i]!=S[i-1]):
        lis.append(len(tmp))
        tmp =S[i]
    else:
        tmp+=S[i]
lis.append(len(tmp))
#0で終わっていたら最後に１が0個であるとする
if("0" in tmp):
    lis.append(0)
# print(lis)

#累積和をとる
L = len(lis)
# print(L)
asum = [0]*(L+1)
asum[0] = 0
for i in range(1,L+1):
    asum[i] = asum[i-1] + lis[i-1]
# print(asum)

#尺をとる
l = 0
ans = max(lis) if l+2*K+1 < L+1 else sum(lis)
for r in range(l+2*K+1 , L+1,2):
    # print(l,r)
    # print(asum[r] - asum[l])
    ans = max(asum[r] - asum[l],ans)
    l+=2
print(ans)

# 14 2
# 11101010110011
# 10 1
# 0000000001


from __future__ import division
import os
import numpy as np
import matplotlib.pyplot as plt

from ephys.objects.extra_cells import *
from ephys.utils.sound_objects import *
from ephys.objects.traversal import *
from ephys.utils.figures import *
from ephys.figures.exploratory import *
from lasp.signal import smooth_signal
from lasp.spikes import compute_psth

save_dir = "/auto/k8/tlee/ephys/analyses/paired_responses"

def get_paired_sounds(songA, songB):

    soundsA = get_sounds_by_song_name(songA.f, songA.name)
    sounds = list()
    for sound in soundsA:
        ps = get_individual_paired_song(songB, sound)
        if ps is not None:
            sounds.append(ps.sound)
    return sounds

class PairedSongs():

    def __init__(self, f, songA, songB):

        self.f = f
        s = Song(f)
        s.from_name(songA)
        self.songA = s
        s = Song(f)
        s.from_name(songB)
        self.songB = s

        self.sounds = get_paired_sounds(self.songA, self.songB)

    def get_cell_responses(self, site_id, smooth_dur=0):

        site = Site(self.f)
        site.from_id(site_id)
        sound_ids = [s.id for s in self.sounds]

        responses = list()
        stimuli = list()
        for protocol in site.protocols:
            for se in protocol.events:
                if se.sound_id in sound_ids:
                    stimuli.append(se)
                    start, stop = se.start_time, se.end_time
                    psths = list()
                    for cpr in protocol.cell_protocol_responses:
                        spikes = cpr.spikes[(cpr.spikes >= start) & (cpr.spikes <= stop)] - start
                        psth = compute_psth([spikes], se.sound.duration)[1]
                        if smooth_dur > 0:
                            psth = smooth_signal(psth, smooth_dur, np.floor(smooth_dur / 2))
                        psths.append(psth)
                    responses.append(psths)

        self.site = site
        self.responses = responses
        self.stimuli = stimuli
        self.order_responses()
        self.response_sr = 1000.0

    def get_lfp_responses(self, site_id):

        site = Site(self.f)
        site.from_id(site_id)
        sound_ids = [s.id for s in self.sounds]

        responses = list()
        stimuli = list()
        lfp_sr = site.protocols[0].lfp_protocol_responses[0].lfp.sample_rate

        for protocol in site.protocols:
            for se in protocol.events:
                if se.sound_id in sound_ids:
                    stimuli.append(se)
                    start, stop = se.start_time, se.end_time
                    lfps = lists()
                    for lfppr in protocol.lfp_protocol_responses:
                        lfp = lfppr.waveform
                        # Add filtering or whatever here
                        lfps.append(lfp)
                    responses.append(lfps)

        self.site = site
        self.responses = responses
        self.stimuli = stimuli
        self.order_responses()
        self.response_sr = lfp_sr

    def plot_exploratory(self, focus_on=None, order_by_type=False):

        # If focus is not None, set onsets and offsets to focus on songA or songB

        if order_by_type:
            self.order_sounds()

        sounds = [se.sound for se in self.stimuli]
        if focus_on is None:
            single_trial_responses(sounds, self.responses)

    def order_responses(self):

        emap = get_electrode_map(self.stimuli[0])
        order = sort_emap_for_subplots(emap)
        self.responses = [[rr[ii - 1] for ii in order] for rr in self.responses]

    def order_sounds(self, a_first=True):

        sort_values = list()
        for se, response in zip(self.stimuli, self.responses):
            if a_first:
                ps1 = get_individual_paired_song(self.songA, se.sound)
                ps2 = get_individual_paired_song(self.songB, se.sound)
            else:
                ps2 = get_individual_paired_song(self.songA, se.sound)
                ps1 = get_individual_paired_song(self.songB, se.sound)

            if ps1.overlap_type == "nonoverlapping":
                sort_values.append((0, ps1.start, se, response))
            elif ps1.overlap_type == "simultaneous":
                sort_values.append((2, 0.0, se, response))
            elif ps1.overlap_type == "overlapping":
                if ps1.order == 0:
                    sort_values.append((1, -ps2.start, se, response))
                else:
                    sort_values.append((3, ps1.start, se, response))

        sort_values.sort(key=lambda x: x[1])
        sort_values.sort(key=lambda x: x[0])

        self.stimuli, self.responses = zip(*sort_values)[2:]
        self.stimuli = list(self.stimuli)
        self.responses = list(self.responses)

    def get_on_times(self, songA=True):

        start = list()
        stop = list()
        for se in self.stimuli:
            if songA:
                ps = get_individual_paired_song(self.songA, se.sound)
                dur = self.songA.duration
            else:
                ps = get_individual_paired_song(self.songB, se.sound)
                dur = self.songB.duration

            start.append(int(ps.start * self.response_sr))
            stop.append(int(ps.start * self.response_sr) + int(dur * self.response_sr))

        return start, stop

    def plot_rasters_by_cell(self, focus_on="A", save=False, tag=""):

        self.order_sounds()
        if focus_on == "A":
            starts, stops = self.get_on_times()
            spec = self.songA.spectrogram.data
            f = self.songA.spectrogram.frequency / 1000
            t = np.arange(spec.shape[1]) / self.songA.spectrogram.sample_rate
        else:
            starts, stops = self.get_on_times(False)
            spec = self.songB.spectrogram.data
            f = self.songB.spectrogram.frequency / 1000
            t = np.arange(spec.shape[1]) / self.songB.spectrogram.sample_rate

        nUnits = len(self.responses[0])
        # rasters = list()

        diff_overlap = lambda se0, se1: se0.sound.paired_sounds[0].overlap_type != se1.sound.paired_sounds[0].overlap_type
        lines = [(ii + .5, ii + .5) for ii, se0, se1 in zip(range(len(self.stimuli) - 1), self.stimuli[:-1], self.stimuli[1:]) if diff_overlap(se0, se1)]

        fig = plt.figure(facecolor="white")
        ax = fig.add_subplot(9, 2, 1)
        plot_spectrogram(t, f, spec, ax=ax, fmin=f.min(), fmax=f.max(), colormap=plt.cm.spectral, colorbar=False)
        ax.set_yticks(ax.get_yticks()[::2])
        ax.set_xticks([])

        ax = fig.add_subplot(9, 2, 2)
        plot_spectrogram(t, f, spec, ax=ax, fmin=f.min(), fmax=f.max(), colormap=plt.cm.spectral, colorbar=False)
        ax.set_yticks(ax.get_yticks()[::2])
        ax.set_xticks([])

        for ii in range(nUnits):
            raster = np.array([r[ii][start:stop] for r, start, stop in zip(self.responses, starts, stops)])
            raster[raster > 0] = 1
            ax = fig.add_subplot(9, 2, ii + 3)
            ax.imshow(raster, aspect="auto", cmap=plt.cm.binary, interpolation='none')
            for l in lines:
                ax.plot((0, raster.shape[1]), l, color="grey")
            ax.set_yticks([])
            ax.set_xticks(ax.get_xticks()[::2])
            ax.set_ylim((-0.5, raster.shape[0] + 0.5))
            ax.set_xlim((0, raster.shape[1]))
            ax.invert_yaxis()
            if ii < nUnits - 2:
                ax.set_xticks([])
            for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()):
                item.set_fontsize(12)
            # rasters.append(raster)

        if save:
            fname = os.path.join(save_dir, "ByCell_%s_%s_%s_%s%s.pdf" % (focus_on, self.songA.name, self.songB.name, self.site.name, tag))
            fig.savefig(fname, facecolor="white", edgecolor="white", dpi=300, format="pdf")

    def plot_rasters_by_stim(self, focus_on="A", save=False, tag=""):

        overlap_colors = {"nonoverlapping": "b", "overlapping": "r", "simultaneous": "c"}
        self.order_sounds()
        if focus_on == "A":
            starts, stops = self.get_on_times()
        else:
            starts, stops = self.get_on_times(False)

        # rasters = list()
        nStim = len(self.stimuli)
        nRows = np.floor(np.sqrt(nStim))
        nCols = np.ceil(nStim / nRows)

        fig = plt.figure(facecolor="white")
        for ii, start, stop in zip(range(nStim), starts, stops):
            c = overlap_colors[self.stimuli[ii].sound.paired_sounds[0].overlap_type]
            raster = np.array(self.responses[ii])[:, start: stop]
            raster[raster > 0] = 1
            ax = fig.add_subplot(nRows, nCols, ii + 1)
            ax.imshow(raster, aspect="auto", cmap=plt.cm.binary, interpolation='none')
            ax.set_yticks(ax.get_yticks()[::2])
            ax.set_xticks(ax.get_xticks()[::2])
            ax.set_ylim((-.5, raster.shape[0]))
            ax.set_xlim((0, raster.shape[1]))
            if np.floor((ii + 1) / nRows) != np.floor(nStim / nRows):
                ax.set_xticks([])
            for spine in ax.spines.values():
                spine.set_color(c)
            for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()):
                item.set_fontsize(12)

        if save:
            fname = os.path.join(save_dir, "ByStim_%s_%s_%s_%s%s.pdf" % (focus_on, self.songA.name, self.songB.name, self.site.name, tag))
            fig.savefig(fname, facecolor="white", edgecolor="white", dpi=300, format="pdf")


# uncompyle6 version 3.7.4
# Python bytecode 3.5 (3351)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/max/code/oss/hyperopt/hyperopt/tpe.py
# Compiled at: 2019-10-17 07:38:06
# Size of source mod 2**32: 32007 bytes
"""
Graphical model (GM)-based optimization algorithm using Theano
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from builtins import str
from builtins import map
from builtins import zip
from builtins import range
from past.utils import old_div
import logging, time, numpy as np
from scipy.special import erf
from . import pyll
from .pyll import scope
from .pyll.stochastic import implicit_stochastic
from .base import miscs_to_idxs_vals
from .base import miscs_update_idxs_vals
from . import rand
__authors__ = 'James Bergstra'
__license__ = '3-clause BSD License'
__contact__ = 'github.com/jaberg/hyperopt'
logger = logging.getLogger(__name__)
EPS = 1e-12
DEFAULT_LF = 25
adaptive_parzen_samplers = {}

def adaptive_parzen_sampler(name):

    def wrapper(f):
        assert name not in adaptive_parzen_samplers
        adaptive_parzen_samplers[name] = f
        return f

    return wrapper

@scope.define
def categorical_lpdf(sample, p, upper):
    """
    """
    if sample.size:
        return np.log(np.asarray(p)[sample])
    else:
        return np.asarray([])

@implicit_stochastic
@scope.define
def GMM1(weights, mus, sigmas, low=None, high=None, q=None, rng=None, size=()):
    """Sample from truncated 1-D Gaussian Mixture Model"""
    weights, mus, sigmas = list(map(np.asarray, (weights, mus, sigmas)))
    assert len(weights) == len(mus) == len(sigmas)
    n_samples = int(np.prod(size))
    if low is None and high is None:
        active = np.argmax(rng.multinomial(1, weights, (n_samples,)), axis=1)
        samples = rng.normal(loc=mus[active], scale=sigmas[active])
    else:
        low = float(low) if low is not None else -float('Inf')
        high = float(high) if high is not None else float('Inf')
        if low >= high:
            raise ValueError('low >= high', (low, high))
        samples = []
        while len(samples) < n_samples:
            active = np.argmax(rng.multinomial(1, weights))
            draw = rng.normal(loc=mus[active], scale=sigmas[active])
            if low <= draw < high:
                samples.append(draw)

    samples = np.reshape(np.asarray(samples), size)
    if q is None:
        return samples
    else:
        return np.round(old_div(samples, q)) * q

@scope.define
def normal_cdf(x, mu, sigma):
    top = x - mu
    bottom = np.maximum(np.sqrt(2) * sigma, EPS)
    z = old_div(top, bottom)
    return 0.5 * (1 + erf(z))

@scope.define
def GMM1_lpdf(samples, weights, mus, sigmas, low=None, high=None, q=None):
    verbose = 0
    samples, weights, mus, sigmas = list(map(np.asarray, (
     samples, weights, mus, sigmas)))
    if samples.size == 0:
        return np.asarray([])
    if weights.ndim != 1:
        raise TypeError('need vector of weights', weights.shape)
    if mus.ndim != 1:
        raise TypeError('need vector of mus', mus.shape)
    if sigmas.ndim != 1:
        raise TypeError('need vector of sigmas', sigmas.shape)
    assert len(weights) == len(mus) == len(sigmas)
    _samples = samples
    samples = _samples.flatten()
    if verbose:
        print('GMM1_lpdf:samples', set(samples))
        print('GMM1_lpdf:weights', weights)
        print('GMM1_lpdf:mus', mus)
        print('GMM1_lpdf:sigmas', sigmas)
        print('GMM1_lpdf:low', low)
        print('GMM1_lpdf:high', high)
        print('GMM1_lpdf:q', q)
    if low is None and high is None:
        p_accept = 1
    else:
        p_accept = np.sum(weights * (normal_cdf(high, mus, sigmas) - normal_cdf(low, mus, sigmas)))
    if q is None:
        dist = samples[:, None] - mus
        mahal = old_div(dist, np.maximum(sigmas, EPS)) ** 2
        Z = np.sqrt(2 * np.pi * sigmas ** 2)
        coef = weights / Z / p_accept
        rval = logsum_rows(-0.5 * mahal + np.log(coef))
    else:
        prob = np.zeros(samples.shape, dtype='float64')
        for w, mu, sigma in zip(weights, mus, sigmas):
            if high is None:
                ubound = samples + old_div(q, 2.0)
            else:
                ubound = np.minimum(samples + old_div(q, 2.0), high)
            if low is None:
                lbound = samples - old_div(q, 2.0)
            else:
                lbound = np.maximum(samples - old_div(q, 2.0), low)
            inc_amt = w * normal_cdf(ubound, mu, sigma)
            inc_amt -= w * normal_cdf(lbound, mu, sigma)
            prob += inc_amt

        rval = np.log(prob) - np.log(p_accept)
    if verbose:
        print('GMM1_lpdf:rval:', dict(list(zip(samples, rval))))
    rval.shape = _samples.shape
    return rval

@scope.define
def lognormal_cdf(x, mu, sigma):
    if len(x) == 0:
        return np.asarray([])
    if x.min() < 0:
        raise ValueError('negative arg to lognormal_cdf', x)
    olderr = np.seterr(divide='ignore')
    try:
        top = np.log(np.maximum(x, EPS)) - mu
        bottom = np.maximum(np.sqrt(2) * sigma, EPS)
        z = old_div(top, bottom)
        return 0.5 + 0.5 * erf(z)
    finally:
        np.seterr(**olderr)

@scope.define
def lognormal_lpdf(x, mu, sigma):
    assert np.all(sigma >= 0)
    sigma = np.maximum(sigma, EPS)
    Z = sigma * x * np.sqrt(2 * np.pi)
    E = 0.5 * old_div(np.log(x) - mu, sigma) ** 2
    rval = -E - np.log(Z)
    return rval

@scope.define
def qlognormal_lpdf(x, mu, sigma, q):
    return np.log(lognormal_cdf(x, mu, sigma) - lognormal_cdf(x - q, mu, sigma))

@implicit_stochastic
@scope.define
def LGMM1(weights, mus, sigmas, low=None, high=None, q=None, rng=None, size=()):
    weights, mus, sigmas = list(map(np.asarray, (weights, mus, sigmas)))
    n_samples = np.prod(size)
    if low is None and high is None:
        active = np.argmax(rng.multinomial(1, weights, (n_samples,)), axis=1)
        assert len(active) == n_samples
        samples = np.exp(rng.normal(loc=mus[active], scale=sigmas[active]))
    else:
        low = float(low)
        high = float(high)
        if low >= high:
            raise ValueError('low >= high', (low, high))
        samples = []
        while len(samples) < n_samples:
            active = np.argmax(rng.multinomial(1, weights))
            draw = rng.normal(loc=mus[active], scale=sigmas[active])
            if low <= draw < high:
                samples.append(np.exp(draw))

        samples = np.asarray(samples)
    samples = np.reshape(np.asarray(samples), size)
    if q is not None:
        samples = np.round(old_div(samples, q)) * q
    return samples

def logsum_rows(x):
    R, C = x.shape
    m = x.max(axis=1)
    return np.log(np.exp(x - m[:, None]).sum(axis=1)) + m

@scope.define
def LGMM1_lpdf(samples, weights, mus, sigmas, low=None, high=None, q=None):
    samples, weights, mus, sigmas = list(map(np.asarray, (
     samples, weights, mus, sigmas)))
    assert weights.ndim == 1
    assert mus.ndim == 1
    assert sigmas.ndim == 1
    _samples = samples
    if samples.ndim != 1:
        samples = samples.flatten()
    if low is None and high is None:
        p_accept = 1
    else:
        p_accept = np.sum(weights * (normal_cdf(high, mus, sigmas) - normal_cdf(low, mus, sigmas)))
    if q is None:
        lpdfs = lognormal_lpdf(samples[:, None], mus, sigmas)
        rval = logsum_rows(lpdfs + np.log(weights))
    else:
        prob = np.zeros(samples.shape, dtype='float64')
        for w, mu, sigma in zip(weights, mus, sigmas):
            if high is None:
                ubound = samples + old_div(q, 2.0)
            else:
                ubound = np.minimum(samples + old_div(q, 2.0), np.exp(high))
            if low is None:
                lbound = samples - old_div(q, 2.0)
            else:
                lbound = np.maximum(samples - old_div(q, 2.0), np.exp(low))
            lbound = np.maximum(0, lbound)
            inc_amt = w * lognormal_cdf(ubound, mu, sigma)
            inc_amt -= w * lognormal_cdf(lbound, mu, sigma)
            prob += inc_amt

        rval = np.log(prob) - np.log(p_accept)
    rval.shape = _samples.shape
    return rval

@scope.define_info(o_len=3)
def adaptive_parzen_normal_orig(mus, prior_weight, prior_mu, prior_sigma):
    """
    A heuristic estimator for the mu and sigma values of a GMM
    TODO: try to find this heuristic in the literature, and cite it - Yoshua
    mentioned the term 'elastic' I think?

    mus - matrix (N, M) of M, N-dimensional component centers
    """
    mus_orig = np.array(mus)
    mus = np.array(mus)
    assert str(mus.dtype) != 'object'
    if mus.ndim != 1:
        raise TypeError('mus must be vector', mus)
    if len(mus) == 0:
        mus = np.asarray([prior_mu])
        sigma = np.asarray([prior_sigma])
    else:
        if len(mus) == 1:
            mus = np.asarray([prior_mu] + [mus[0]])
            sigma = np.asarray([prior_sigma, prior_sigma * 0.5])
        elif len(mus) >= 2:
            order = np.argsort(mus)
            mus = mus[order]
            sigma = np.zeros_like(mus)
            sigma[1:-1] = np.maximum(mus[1:-1] - mus[0:-2], mus[2:] - mus[1:-1])
            if len(mus) > 2:
                lsigma = mus[2] - mus[0]
                usigma = mus[(-1)] - mus[(-3)]
            else:
                lsigma = mus[1] - mus[0]
                usigma = mus[(-1)] - mus[(-2)]
            sigma[0] = lsigma
            sigma[-1] = usigma
            mus[order] = mus.copy()
            sigma[order] = sigma.copy()
            if not np.all(mus_orig == mus):
                print('orig', mus_orig)
                print('mus', mus)
            assert np.all(mus_orig == mus)
            mus = np.asarray([prior_mu] + list(mus))
            sigma = np.asarray([prior_sigma] + list(sigma))
    maxsigma = prior_sigma
    minsigma = old_div(prior_sigma, np.sqrt(1 + len(mus)))
    sigma = np.clip(sigma, minsigma, maxsigma)
    weights = np.ones(len(mus), dtype=mus.dtype)
    weights[0] = prior_weight
    weights = old_div(weights, weights.sum())
    return (
     weights, mus, sigma)

@scope.define
def linear_forgetting_weights(N, LF):
    assert N >= 0
    assert LF > 0
    if N == 0:
        return np.asarray([])
    else:
        if N < LF:
            return np.ones(N)
        ramp = np.linspace(old_div(1.0, N), 1.0, num=N - LF)
        flat = np.ones(LF)
        weights = np.concatenate([ramp, flat], axis=0)
        assert weights.shape == (N,), (weights.shape, N)
        return weights

@scope.define_info(o_len=3)
def adaptive_parzen_normal(mus, prior_weight, prior_mu, prior_sigma, LF=DEFAULT_LF):
    """
    mus - matrix (N, M) of M, N-dimensional component centers
    """
    mus = np.array(mus)
    assert str(mus.dtype) != 'object'
    if mus.ndim != 1:
        raise TypeError('mus must be vector', mus)
    if len(mus) == 0:
        srtd_mus = np.asarray([prior_mu])
        sigma = np.asarray([prior_sigma])
        prior_pos = 0
    else:
        if len(mus) == 1:
            if prior_mu < mus[0]:
                prior_pos = 0
                srtd_mus = np.asarray([prior_mu, mus[0]])
                sigma = np.asarray([prior_sigma, prior_sigma * 0.5])
            else:
                prior_pos = 1
                srtd_mus = np.asarray([mus[0], prior_mu])
                sigma = np.asarray([prior_sigma * 0.5, prior_sigma])
        else:
            if len(mus) >= 2:
                order = np.argsort(mus)
                prior_pos = np.searchsorted(mus[order], prior_mu)
                srtd_mus = np.zeros(len(mus) + 1)
                srtd_mus[:prior_pos] = mus[order[:prior_pos]]
                srtd_mus[prior_pos] = prior_mu
                srtd_mus[prior_pos + 1:] = mus[order[prior_pos:]]
                sigma = np.zeros_like(srtd_mus)
                sigma[1:-1] = np.maximum(srtd_mus[1:-1] - srtd_mus[0:-2], srtd_mus[2:] - srtd_mus[1:-1])
                lsigma = srtd_mus[1] - srtd_mus[0]
                usigma = srtd_mus[(-1)] - srtd_mus[(-2)]
                sigma[0] = lsigma
                sigma[-1] = usigma
            if LF and LF < len(mus):
                unsrtd_weights = linear_forgetting_weights(len(mus), LF)
                srtd_weights = np.zeros_like(srtd_mus)
                assert len(unsrtd_weights) + 1 == len(srtd_mus)
                srtd_weights[:prior_pos] = unsrtd_weights[order[:prior_pos]]
                srtd_weights[prior_pos] = prior_weight
                srtd_weights[prior_pos + 1:] = unsrtd_weights[order[prior_pos:]]
            else:
                srtd_weights = np.ones(len(srtd_mus))
                srtd_weights[prior_pos] = prior_weight
            maxsigma = old_div(prior_sigma, 1.0)
            minsigma = old_div(prior_sigma, min(100.0, 1.0 + len(srtd_mus)))
            sigma = np.clip(sigma, minsigma, maxsigma)
            sigma[prior_pos] = prior_sigma
            assert prior_sigma > 0
            assert maxsigma > 0
            if not minsigma > 0:
                raise AssertionError
        if not np.all(sigma > 0):
            raise AssertionError((sigma.min(), minsigma, maxsigma))
    srtd_weights /= srtd_weights.sum()
    return (
     srtd_weights, srtd_mus, sigma)

@adaptive_parzen_sampler('uniform')
def ap_uniform_sampler(obs, prior_weight, low, high, size=(), rng=None):
    prior_mu = 0.5 * (high + low)
    prior_sigma = 1.0 * (high - low)
    weights, mus, sigmas = scope.adaptive_parzen_normal(obs, prior_weight, prior_mu, prior_sigma)
    return scope.GMM1(weights, mus, sigmas, low=low, high=high, q=None, size=size, rng=rng)

@adaptive_parzen_sampler('quniform')
def ap_quniform_sampler(obs, prior_weight, low, high, q, size=(), rng=None):
    prior_mu = 0.5 * (high + low)
    prior_sigma = 1.0 * (high - low)
    weights, mus, sigmas = scope.adaptive_parzen_normal(obs, prior_weight, prior_mu, prior_sigma)
    return scope.GMM1(weights, mus, sigmas, low=low, high=high, q=q, size=size, rng=rng)

@adaptive_parzen_sampler('loguniform')
def ap_loguniform_sampler(obs, prior_weight, low, high, size=(), rng=None):
    prior_mu = 0.5 * (high + low)
    prior_sigma = 1.0 * (high - low)
    weights, mus, sigmas = scope.adaptive_parzen_normal(scope.log(obs), prior_weight, prior_mu, prior_sigma)
    rval = scope.LGMM1(weights, mus, sigmas, low=low, high=high, size=size, rng=rng)
    return rval

@adaptive_parzen_sampler('qloguniform')
def ap_qloguniform_sampler(obs, prior_weight, low, high, q, size=(), rng=None):
    prior_mu = 0.5 * (high + low)
    prior_sigma = 1.0 * (high - low)
    weights, mus, sigmas = scope.adaptive_parzen_normal(scope.log(scope.maximum(obs, scope.maximum(EPS, scope.exp(low)))), prior_weight, prior_mu, prior_sigma)
    return scope.LGMM1(weights, mus, sigmas, low, high, q=q, size=size, rng=rng)

@adaptive_parzen_sampler('normal')
def ap_normal_sampler(obs, prior_weight, mu, sigma, size=(), rng=None):
    weights, mus, sigmas = scope.adaptive_parzen_normal(obs, prior_weight, mu, sigma)
    return scope.GMM1(weights, mus, sigmas, size=size, rng=rng)

@adaptive_parzen_sampler('qnormal')
def ap_qnormal_sampler(obs, prior_weight, mu, sigma, q, size=(), rng=None):
    weights, mus, sigmas = scope.adaptive_parzen_normal(obs, prior_weight, mu, sigma)
    return scope.GMM1(weights, mus, sigmas, q=q, size=size, rng=rng)

@adaptive_parzen_sampler('lognormal')
def ap_loglognormal_sampler(obs, prior_weight, mu, sigma, size=(), rng=None):
    weights, mus, sigmas = scope.adaptive_parzen_normal(scope.log(obs), prior_weight, mu, sigma)
    rval = scope.LGMM1(weights, mus, sigmas, size=size, rng=rng)
    return rval

@adaptive_parzen_sampler('qlognormal')
def ap_qlognormal_sampler(obs, prior_weight, mu, sigma, q, size=(), rng=None):
    log_obs = scope.log(scope.maximum(obs, EPS))
    weights, mus, sigmas = scope.adaptive_parzen_normal(log_obs, prior_weight, mu, sigma)
    rval = scope.LGMM1(weights, mus, sigmas, q=q, size=size, rng=rng)
    return rval

@adaptive_parzen_sampler('randint')
def ap_categorical_sampler(obs, prior_weight, upper, size=(), rng=None, LF=DEFAULT_LF):
    weights = scope.linear_forgetting_weights(scope.len(obs), LF=LF)
    counts = scope.bincount(obs, minlength=upper, weights=weights)
    pseudocounts = counts + prior_weight
    return scope.categorical(old_div(pseudocounts, scope.sum(pseudocounts)), upper=upper, size=size, rng=rng)

@scope.define
def tpe_cat_pseudocounts(counts, upper, prior_weight, p, size):
    if size == 0 or np.prod(size) == 0:
        return []
    if p.ndim == 2:
        assert np.all(p == p[0])
        p = p[0]
    pseudocounts = counts + upper * (prior_weight * p)
    return old_div(pseudocounts, np.sum(pseudocounts))

@adaptive_parzen_sampler('categorical')
def ap_categorical_sampler(obs, prior_weight, p, upper=None, size=(), rng=None, LF=DEFAULT_LF):
    weights = scope.linear_forgetting_weights(scope.len(obs), LF=LF)
    counts = scope.bincount(obs, minlength=upper, weights=weights)
    pseudocounts = scope.tpe_cat_pseudocounts(counts, upper, prior_weight, p, size)
    return scope.categorical(pseudocounts, upper=upper, size=size, rng=rng)

@scope.define_info(o_len=2)
def ap_filter_trials(o_idxs, o_vals, l_idxs, l_vals, gamma, gamma_cap=DEFAULT_LF):
    """Return the elements of o_vals that correspond to trials whose losses
    were above gamma, or below gamma.
    """
    o_idxs, o_vals, l_idxs, l_vals = list(map(np.asarray, [
     o_idxs, o_vals, l_idxs, l_vals]))
    n_below = min(int(np.ceil(gamma * np.sqrt(len(l_vals)))), gamma_cap)
    l_order = np.argsort(l_vals)
    keep_idxs = set(l_idxs[l_order[:n_below]])
    below = [v for i, v in zip(o_idxs, o_vals) if i in keep_idxs]
    keep_idxs = set(l_idxs[l_order[n_below:]])
    above = [v for i, v in zip(o_idxs, o_vals) if i in keep_idxs]
    return (
     np.asarray(below), np.asarray(above))

def build_posterior(specs, prior_idxs, prior_vals, obs_idxs, obs_vals, oloss_idxs, oloss_vals, oloss_gamma, prior_weight):
    """
    This method clones a posterior inference graph by iterating forward in
    topological order, and replacing prior random-variables (prior_vals) with
    new posterior distributions that make use of observations (obs_vals).

    """
    assert all(isinstance(arg, pyll.Apply) for arg in [oloss_idxs, oloss_vals, oloss_gamma])
    expr = pyll.as_apply([specs, prior_idxs, prior_vals])
    nodes = pyll.dfs(expr)
    memo = {}
    obs_memo = {}
    for nid in prior_vals:
        obs_below, obs_above = scope.ap_filter_trials(obs_idxs[nid], obs_vals[nid], oloss_idxs, oloss_vals, oloss_gamma)
        obs_memo[prior_vals[nid]] = [obs_below, obs_above]

    for node in nodes:
        if node not in memo:
            new_inputs = [memo[arg] for arg in node.inputs()]
            if node in obs_memo:
                obs_below, obs_above = obs_memo[node]
                aa = [memo[a] for a in node.pos_args]
                fn = adaptive_parzen_samplers[node.name]
                b_args = [obs_below, prior_weight] + aa
                named_args = [[kw, memo[arg]] for kw, arg in node.named_args]
                b_post = fn(*b_args, **dict(named_args))
                a_args = [obs_above, prior_weight] + aa
                a_post = fn(*a_args, **dict(named_args))
                assert a_post.name == b_post.name
                fn_lpdf = getattr(scope, a_post.name + '_lpdf')
                a_kwargs = dict([(n, a) for n, a in a_post.named_args if n not in ('rng',
                                                                                'size')])
                b_kwargs = dict([(n, a) for n, a in b_post.named_args if n not in ('rng',
                                                                                'size')])
                below_llik = fn_lpdf(*[b_post] + b_post.pos_args, **b_kwargs)
                above_llik = fn_lpdf(*[b_post] + a_post.pos_args, **a_kwargs)
                new_node = scope.broadcast_best(b_post, below_llik, above_llik)
            else:
                if hasattr(node, 'obj'):
                    new_node = node
                else:
                    new_node = node.clone_from_inputs(new_inputs)
                memo[node] = new_node

    post_specs = memo[specs]
    post_idxs = dict([(nid, memo[idxs]) for nid, idxs in list(prior_idxs.items())])
    post_vals = dict([(nid, memo[vals]) for nid, vals in list(prior_vals.items())])
    assert set(post_idxs.keys()) == set(post_vals.keys())
    assert set(post_idxs.keys()) == set(prior_idxs.keys())
    return (post_specs, post_idxs, post_vals)

@scope.define
def idxs_prod(full_idxs, idxs_by_label, llik_by_label):
    """Add all of the  log-likelihoods together by id.

    Example arguments:
    full_idxs = [0, 1, ... N-1]
    idxs_by_label = {'node_a': [1, 3], 'node_b': [3]}
    llik_by_label = {'node_a': [0.1, -3.3], node_b: [1.0]}

    This would return N elements: [0, 0.1, 0, -2.3, 0, 0, ... ]
    """
    assert len(set(full_idxs)) == len(full_idxs)
    full_idxs = list(full_idxs)
    rval = np.zeros(len(full_idxs))
    pos_of_tid = dict(list(zip(full_idxs, list(range(len(full_idxs))))))
    assert set(idxs_by_label.keys()) == set(llik_by_label.keys())
    for nid in idxs_by_label:
        idxs = idxs_by_label[nid]
        llik = llik_by_label[nid]
        assert np.all(np.asarray(idxs) > 1)
        assert len(set(idxs)) == len(idxs)
        assert len(idxs) == len(llik)
        for ii, ll in zip(idxs, llik):
            rval[pos_of_tid[ii]] += ll

    return rval

@scope.define
def broadcast_best(samples, below_llik, above_llik):
    if len(samples):
        score = below_llik - above_llik
        if len(samples) != len(score):
            raise ValueError()
        best = np.argmax(score)
        return [
         samples[best]] * len(samples)
    else:
        return []

_default_prior_weight = 1.0
_default_n_EI_candidates = 24
_default_gamma = 0.25
_default_n_startup_jobs = 20
_default_linear_forgetting = DEFAULT_LF

def tpe_transform(domain, prior_weight, gamma):
    s_prior_weight = pyll.Literal(float(prior_weight))
    observed = dict(idxs=pyll.Literal(), vals=pyll.Literal())
    observed_loss = dict(idxs=pyll.Literal(), vals=pyll.Literal())
    specs, idxs, vals = build_posterior(domain.vh.v_expr, domain.vh.idxs_by_label(), domain.vh.vals_by_label(), observed['idxs'], observed['vals'], observed_loss['idxs'], observed_loss['vals'], pyll.Literal(gamma), s_prior_weight)
    return (
     s_prior_weight, observed, observed_loss,
     specs, idxs, vals)

def suggest(new_ids, domain, trials, seed, prior_weight=_default_prior_weight, n_startup_jobs=_default_n_startup_jobs, n_EI_candidates=_default_n_EI_candidates, gamma=_default_gamma, linear_forgetting=_default_linear_forgetting):
    new_id = new_ids[0]
    t0 = time.time()
    s_prior_weight, observed, observed_loss, specs, opt_idxs, opt_vals = tpe_transform(domain, prior_weight, gamma)
    tt = time.time() - t0
    logger.info('tpe_transform took %f seconds' % tt)
    best_docs = dict()
    best_docs_loss = dict()
    for doc in trials.trials:
        tid = doc['misc'].get('from_tid', doc['tid'])
        loss = domain.loss(doc['result'], doc['spec'])
        if loss is None:
            loss = float('inf')
        else:
            loss = float(loss)
        best_docs_loss.setdefault(tid, loss)
        if loss <= best_docs_loss[tid]:
            best_docs_loss[tid] = loss
            best_docs[tid] = doc

    tid_docs = list(best_docs.items())
    tid_docs.sort()
    losses = [best_docs_loss[k] for k, v in tid_docs]
    tids = [k for k, v in tid_docs]
    docs = [v for k, v in tid_docs]
    if docs:
        logger.info('TPE using %i/%i trials with best loss %f' % (
         len(docs), len(trials), min(best_docs_loss.values())))
    else:
        logger.info('TPE using 0 trials')
    if len(docs) < n_startup_jobs:
        return rand.suggest(new_ids, domain, trials, seed)
    if tids:
        fake_id_0 = max(max(tids), new_id) + 2
    else:
        assert n_startup_jobs <= 0
        fake_id_0 = new_id + 2
    fake_ids = list(range(fake_id_0, fake_id_0 + n_EI_candidates))
    memo = {domain.s_new_ids: fake_ids,
     domain.s_rng: np.random.RandomState(seed)}
    o_idxs_d, o_vals_d = miscs_to_idxs_vals([d['misc'] for d in docs], keys=list(domain.params.keys()))
    memo[observed['idxs']] = o_idxs_d
    memo[observed['vals']] = o_vals_d
    memo[observed_loss['idxs']] = tids
    memo[observed_loss['vals']] = losses
    idxs, vals = pyll.rec_eval([opt_idxs, opt_vals], memo=memo, print_node_on_error=False)
    rval_specs = [
     None]
    rval_results = [domain.new_result()]
    rval_miscs = [dict(tid=new_id, cmd=domain.cmd, workdir=domain.workdir)]
    miscs_update_idxs_vals(rval_miscs, idxs, vals, idxs_map={fake_ids[0]: new_id}, assert_all_vals_used=False)
    rval_docs = trials.new_trial_docs([new_id], rval_specs, rval_results, rval_miscs)
    return rval_docs


"""
LeetCode
Python3
-*- coding: utf-8 -*-

@Problem : 165. Compare Version Numbers
@Difficulty :

@AUTHOR : Yvette WANG

@Description
"""

# medium, v1, 36ms
class Solution:
    def compareVersion(self, version1, version2):
        """
        :type version1: str
        :type version2: str
        :rtype: int
        """

        version1 = version1.split('.')
        version2 = version2.split('.')

        while version1 and version2:
            num1 = int(version1.pop(0))
            num2 = int(version2.pop(0))

            if num1 > num2:
                return 1
            elif num1 < num2:
                return -1

        if version1:
            for num in version1:
                if int(num) > 0:
                    return 1
        elif version2:
            for num in version2:
                if int(num) > 0:
                    return -1

        return 0

if __name__ == "__main__":
    version1 = '1'
    version2 = '1.1'
    print(Solution().compareVersion(version1, version2))


import os
import shutil

# home = r'D:\work_source\CV_Project\datasets\to_haitu_img\20201218_selected'

path_file = r"D:\work_source\CV_Project\datasets\to_haitu_img\20201216_selected\20201216_takeout.txt"
img_output = r"D:\work_source\CV_Project\datasets\to_haitu_img\8_20201216_takeout"

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

with open(path_file, 'r') as f1:
    list1 = f1.readlines()
for i in range(0, len(list1)):
    list1[i] = list1[i].rstrip('\n')

for path in list1:
    # path = os.path.join(home,path)
    shutil.copy(path, os.path.join(img_output, os.path.basename(path)))


import sys
import io
import time
import socket
import os

import stem.process
from stem.util import term
from stem import Signal
from stem.control import Controller
from stem import CircStatus

import const_config

from itertools import count
#-------------------------------------------------------------------------------
# BootStrap
def print_bootstarp_lines(line):
    #print("line:" + line)
    #Jul 10 19:31:06.000 [notice] Bootstrapped 90%: Establishing a Tor circuit
    if "Bootstrapped" in line:
        #print(term.format(line, term.Color.BLUE))
        idx = line.index("Bootstrapped")
        #print(line)
        print("[ {} ]                       [ ---- ][ {} ]".format(time.strftime('%x %X', time.localtime()), line[idx:]))
        sys.stdout.flush()

#-------------------------------------------------------------------------------
# Create
def get_tor_process(socket_port):

    strDataFolder = const_config.get_temp_cache_folder() + str(socket_port)
    try:
        os.stat(strDataFolder)
    except:
        os.makedirs(strDataFolder)

    tor_process = stem.process.launch_tor_with_config(
        config = {
            #'tor_cmd':"C:/Users/junye/Desktop/Tor Browser/Browser/TorBrowser/Tor/Tor.exe",
            'ControlPort': str(7000),
            'SocksPort': str(socket_port),
            'DataDirectory': strDataFolder,
            #'Log': ['DEBUG stdout', 'ERR stderr' ],
            #'ExitNodes':'{ru}',
        },
        init_msg_handler = print_bootstarp_lines,
        timeout = 90,
    )

    #print('Type of Tor Process:', type(tor_process))
    #print('PID of Tor Process:', tor_process.pid)

    return tor_process, socket_port

#-------------------------------------------------------------------------------
# Kill
def kill_tor_process(tor_process):
    tor_process.kill()
    print('Tor Process Killed')

def tor_status():
    control_port = 7000
    with Controller.from_port(port = control_port) as controller:
      controller.authenticate()

      print('---------------------------------------------------------')
      for circ in sorted(controller.get_circuits()):
        if circ.status != CircStatus.BUILT:
          continue

        print("Circuit %s (%s)" % (circ.id, circ.purpose))

        for i, entry in enumerate(circ.path):
          div = '+' if (i == len(circ.path) - 1) else '|'
          fingerprint, nickname = entry

          desc = controller.get_network_status(fingerprint, None)
          address = desc.address if desc else 'unknown'

          print(" %s- %s (%s, %s)" % (div, fingerprint, nickname, address))

#---------------------------------
# Main
if __name__ == "__main__":
    try:
        tor_process = get_tor_process(7001)
        for callcount in count(0):
            print(callcount)
            tor_status()
            sys.stdout.flush()
            time.sleep(10)
    finally:
        kill_tor_process(tor_process)


#!/usr/bin/env python
"""
_injectMonteCarloWorkflow_

"""
from __future__ import print_function

import os
import sys
import threading

from WMCore.WMInit import connectToDB
from WMCore.Configuration import loadConfigurationFile

from WMCore.WMBS.File import File
from WMCore.WMBS.Fileset import Fileset
from WMCore.WMBS.Subscription import Subscription
from WMCore.WMBS.Workflow import Workflow

from WMCore.DataStructs.Run import Run

from WMCore.WMSpec.StdSpecs.MonteCarlo import MonteCarloWorkloadFactory, getTestArguments
from DBSAPI.dbsApi import DbsApi

from WMCore.WMSpec.Makers.TaskMaker import TaskMaker
from WMCore.WorkQueue.WMBSHelper import WMBSHelper

arguments = getTestArguments()
numEvents = None

if len(sys.argv) != 3:
    print("Usage:")
    print("./injectMonteCarloWorkflow.py PROCESSING_VERSION NUM_EVENTS")
    sys.exit(1)
else:
    arguments["ProcessingVersion"] = sys.argv[1]
    numEvents = int(sys.argv[2])

connectToDB()

workloadName = "MonteCarlo-%s" % arguments["ProcessingVersion"]
workloadFile = "MonteCarlo-%s.pkl" % arguments["ProcessingVersion"]
os.mkdir(workloadName)

factory = MonteCarloWorkloadFactory()
workload = factory(workloadName, arguments)
workloadPath = os.path.join(workloadName, workloadFile)
workload.setOwner("sfoulkes@fnal.gov")
workload.setSpecUrl(workloadPath)

# Build a sandbox using TaskMaker
taskMaker = TaskMaker(workload, os.path.join(os.getcwd(), workloadName))
taskMaker.skipSubscription = True
taskMaker.processWorkload()

workload.save(workloadPath)

myThread = threading.currentThread()
myThread.transaction.begin()
for workloadTask in workload.taskIterator():
    inputFileset = Fileset(name = workloadTask.getPathName())
    inputFileset.create()

    virtualFile = File(lfn = "%s-virtual-input" % workloadTask.getPathName(),
                       size = 0, events = numEvents,
                       locations = set(["cmssrm.fnal.gov", "storm-fe-cms.cr.cnaf.infn.it",
                                        "cmssrm-fzk.gridka.de", "srm2.grid.sinica.edu.tw",
                                        "srm-cms.gridpp.rl.ac.uk", "ccsrm.in2p3.fr",
                                        "srmcms.pic.es"]), merged = False)

    myRun = Run(runNumber = 1)
    myRun.lumis.append(1)
    virtualFile.addRun(myRun)
    virtualFile.create()
    inputFileset.addFile(virtualFile)
    inputFileset.commit()

    myWMBSHelper = WMBSHelper(workload)
    myWMBSHelper._createSubscriptionsInWMBS(workloadTask.getPathName())

myThread.transaction.commit()


from __future__ import print_function
from collections import OrderedDict
from functools import partial
import copy

from PySide import QtCore

from .QWfWorker import QWfWorker
from .QWorkflow import QWorkflow
from ..core import pawstools
from ..core.workflow.WfManager import WfManager
from . import qttools

class QWfManager(WfManager,QtCore.QObject):
    """
    A Qt Signal-slot manager for paws Workflows.
    """
    # this signal should emit the name
    # of the new workflow
    wfAdded = QtCore.Signal(str)

    # this signal should emit the name
    # of the workflow that finished.
    wfFinished = QtCore.Signal(str)
    wfStopped = QtCore.Signal(str)

    # a signal for carrying textual output
    # e.g. for message board logging
    emitMessage = QtCore.Signal(str)

    @QtCore.Slot(str)
    def relayMessage(self,msg):
        self.emitMessage.emit(msg)

    @QtCore.Slot(str)
    def launchWorkflow(self,wfname):
        self.run_wf(wfname)

    def __init__(self,qapp):
        super(QWfManager,self).__init__()
        self.app = qapp
        self.wf_running = OrderedDict()

    def add_wf(self,wfname):
        """
        Add a QWorkflow to self.workflows, with key specified by wfname.
        If wfname is not unique (i.e. a workflow with that name already exists),
        this method will overwrite the existing workflow with a new one.
        """
        wf = QWorkflow()
        if not wf.is_tag_valid(wfname):
            raise pawstools.WfNameError(wf.tag_error_message(wfname))
        wf.message_callback = wf.emitMessage.emit
        wf.emitMessage.connect( self.relayMessage )
        #wf.data_callback = wf.emitData.emit
        #wf.emitData.connect( wf.updateItem )
        wf.data_callback = wf.updateItem
        wf.wfFinished.connect( partial(self.stop_wf,wfname) )
        self.workflows[wfname] = wf
        self.wf_running[wfname] = False
        self.wfAdded.emit(wfname)

    def stop_wf(self,wfname):
        self.wf_running[wfname] = False
        self.wfStopped.emit(wfname)

    def run_wf(self,wfname,pool=None):
        wf = self.workflows[wfname]
        stk,diag = wf.execution_stack()
        self.logmethod('preparing workflow {} for execution'.format(wfname))
        self.prepare_wf(wf,stk)
        if pool is None:
            #wf.message_callback = self.logmethod
            #wf.data_callback = None
            self.wf_running[wfname] = True
            wf.execute()
            self.logmethod('execution finished')
        else:
            # Copy the workflow so it can be moved off the main thread.
            # Connect some signals so that the local copy gets updated
            # as the remote copy gets executed.
            # NOTE: This implementation assumes the Workflows are QWorkflows.
            wf_clone = wf.clone_wf()
            wf_clone.message_callback = wf_clone.emitMessage.emit
            wf_clone.emitMessage.connect(self.relayMessage)
            wf_clone.data_callback = wf_clone.emitData.emit
            wf_clone.emitData.connect(wf.updateItem)
            wf_clone.wfFinished.connect( partial(self.stop_wf,wfname) )
            # construct a QRunnable around a copy of the Workflow
            qr = qttools.RunnableExecutor( wf_clone )
            # Call QThreadPool.start(QRunnable) - executes runnable.run()
            self.wf_running[wfname] = True
            pool.start(qr)


import FWCore.ParameterSet.Config as cms

from PhysicsTools.HepMCCandAlgos.genParticles_cfi import *

#from PhysicsTools.TagAndProbe.tag_probe_electron_cfi import *

from RecoEgamma.EgammaHFProducers.hfEMClusteringSequence_cff import *

from Geometry.CMSCommonData.cmsIdealGeometryXML_cff import *

from Geometry.CaloEventSetup.CaloGeometry_cff import *

from Configuration.EventContent.EventContent_cff import *

hfRecoEcalCandidate.Correct = True
##hfRecoEcalCandidate.e9e25Cut = 0
##hfRecoEcalCandidate.intercept2DCut = -99

hfSuperClusterCandidate = hfRecoEcalCandidate.clone()
hfSuperClusterCandidate.e9e25Cut = 0
hfSuperClusterCandidate.intercept2DCut = -99

from ZShape.EffAcc.SmearedElectronsProducer_cfi import *
SmearedElectronsProducer.doSmearing = False

from ZShape.EffAcc.ZEventProducer_cfi import *

#  Calculate efficiency for *SuperClusters passing as GsfElectron*
#
#  Tag           =  isolated GsfElectron with Robust ID, passing HLT, and
#                    within the fiducial volume of ECAL
#  Probe --> Passing Probe   =
#  SC --> GsfElectron --> isolation --> id --> Trigger
#############################################################

    #############################################
    ############  SuperClusters  ################
    #############################################

HybridSuperClusters = cms.EDProducer("ConcreteEcalCandidateProducer",
    src = cms.InputTag("correctedHybridSuperClusters"),
    particleType = cms.string('gamma')
)
EBSuperClusters = cms.EDFilter("CandViewSelector",
    src = cms.InputTag("HybridSuperClusters"),
    cut = cms.string('abs( eta ) < 1.4442')
)

EndcapSuperClusters = cms.EDProducer("ConcreteEcalCandidateProducer",
    src = cms.InputTag("correctedMulti5x5SuperClustersWithPreshower"),
    particleType = cms.string('gamma')
)
EESuperClusters = cms.EDFilter("CandViewSelector",
    src = cms.InputTag("EndcapSuperClusters"),
    cut = cms.string('abs( eta ) > 1.560 & abs( eta ) < 3.0')
)

#HFSuperClusterCands = cms.EDProducer("ConcreteEcalCandidateProducer",
#    src = cms.InputTag("hfEMClusters"),
#    particleType = cms.string('gamma')
#)
#HFSuperClusters = cms.EDFilter("CandViewSelector",
#    src = cms.InputTag("HFSuperClusterCands"),
#    cut = cms.string('abs( eta ) > 3.0')
#)
#theHFSuperClusters = cms.EDFilter("CandViewSelector",
#    src = cms.InputTag("HFSuperClusters"),
#    cut = cms.string('et > 10.0')
#)

theHFSuperClusters = cms.EDFilter("CandViewSelector",
    src = cms.InputTag("hfSuperClusterCandidate"),
    cut = cms.string('et > 10.0')
)

allSuperClusters = cms.EDFilter("CandViewMerger",
    src = cms.VInputTag(cms.InputTag("EBSuperClusters"), cms.InputTag("EESuperClusters"),cms.InputTag("theHFSuperClusters"))
)

thepreSuperClusters = cms.EDFilter("PdgIdAndStatusCandViewSelector",
    src = cms.InputTag("genParticles"),
   # src = cms.InputTag("SmearedElectronsProducer","ZEventParticles"),
    pdgId = cms.vint32(11),
    status = cms.vint32(3)
    #status = cms.vint32(1)
)

# My final selection of superCluster candidates
theSuperClusters = cms.EDFilter("CandViewSelector",
    src = cms.InputTag("allSuperClusters"),
    cut = cms.string('et  > 5.0')
)

theEEHFGapSuperClusters =  cms.EDFilter("CandViewSelector",
    src = cms.InputTag("EESuperClusters"),
    cut = cms.string('(abs( eta ) > 2.5 & abs( eta ) < 3.0)')
)

sc_sequence = cms.Sequence( (HybridSuperClusters * EBSuperClusters + EndcapSuperClusters * EESuperClusters + hfSuperClusterCandidate * theHFSuperClusters) *allSuperClusters * thepreSuperClusters * (theEEHFGapSuperClusters + theSuperClusters))

    #############################################
    ############  GsfElectrons  ################
    #############################################

electrons = cms.EDFilter("ElectronDuplicateRemover",
    src = cms.untracked.string('pixelMatchGsfElectrons'),
    ptMin = cms.untracked.double(20.0),
    EndcapMinEta = cms.untracked.double(1.56),
    ptMax = cms.untracked.double(1000.0),
    BarrelMaxEta = cms.untracked.double(1.4442),
    EndcapMaxEta = cms.untracked.double(3.0)
)

theGsfElectrons = cms.EDFilter("GsfElectronSelector",
    src = cms.InputTag("electrons"),
    cut = cms.string('pt > -10.0')
)

theGsfM1 = cms.EDFilter("GsfElectronSelector",
    src = cms.InputTag("theGsfElectrons"),
    cut = cms.string('abs( eta ) > 0.018 & abs( eta ) < 0.423')
)

theGsfM2 = cms.EDFilter("GsfElectronSelector",
    src = cms.InputTag("theGsfElectrons"),
    cut = cms.string('abs( eta ) > 0.461 & abs( eta ) < 0.770')
)

theGsfM3 = cms.EDFilter("GsfElectronSelector",
    src = cms.InputTag("theGsfElectrons"),
    cut = cms.string('abs( eta ) > 0.806 & abs( eta ) < 1.127')
)

theGsfM4 = cms.EDFilter("GsfElectronSelector",
    src = cms.InputTag("theGsfElectrons"),
    cut = cms.string('abs( eta ) > 1.163 & abs( eta ) < 1.442')
)

theGsfEE = cms.EDFilter("GsfElectronSelector",
    src = cms.InputTag("theGsfElectrons"),
    cut = cms.string('abs( eta ) > 1.56 & abs( eta ) < 3.0')
)

theGsfRap =  cms.EDFilter("GsfElectronSelector",
    src = cms.InputTag("theGsfElectrons"),
    cut = cms.string('( abs( eta ) > 0.018 & abs( eta ) < 0.423 ) || ( abs( eta ) > 0.461 & abs( eta ) < 0.770 ) || ( abs( eta ) > 0.806 & abs( eta ) < 1.127 ) || ( abs( eta ) > 1.163 & abs( eta ) < 1.442 ) || ( abs( eta ) > 1.56 & abs( eta ) < 3.0 )')
)

HFElectronID = cms.EDFilter("CandViewSelector",
    src = cms.InputTag("hfRecoEcalCandidate"),
    cut = cms.string('et > 10.0')
)

theGsfHf = cms.EDFilter("CandViewMerger",
    #src = cms.VInputTag(cms.InputTag("theGsfElectrons"), cms.InputTag("theHFSuperClusters"), cms.InputTag("theEEHFGapSuperClusters"))
    src = cms.VInputTag(cms.InputTag("theGsfElectrons"), cms.InputTag("theHFSuperClusters"))
)

from RecoEgamma.EgammaIsolationAlgos.eleIsoFromDepsModules_cff import *
from RecoEgamma.EgammaIsolationAlgos.eleIsoDepositEcalFromHits_cff import *
from RecoEgamma.EgammaIsolationAlgos.eleIsoDepositHcalFromTowers_cff import *
from RecoEgamma.EgammaIsolationAlgos.eleIsoDepositTk_cff import *
eleIsoDepositTk.src = cms.InputTag('theGsfElectrons') #HERE IS A CHANGE################## theGsfElectrons <-> theGsfRap
eleIsoDepositEcalFromHits.src = cms.InputTag('theTrackerIsolation')
eleIsoDepositHcalFromTowers.src = cms.InputTag('theEcalIsolation')

theTrackerIsolation = cms.EDProducer("IsolatedElectronCandProducer",
        electronProducer = cms.InputTag('theGsfElectrons'), #HERE IS A CHANGE################## theGsfElectrons <-> theGsfRap
        #electronProducer = cms.InputTag('pixelMatchGsfElectrons'),
        IsolationProducer = cms.InputTag('eleIsoFromDepsTk'),
        isoCutEB = cms.double(7.2),
        isoCutEE = cms.double(5.1),
        EBEEBound = cms.double(1.5)
)

theEcalIsolation = cms.EDProducer("IsolatedElectronCandProducer",
        electronProducer = cms.InputTag('theTrackerIsolation'),
        #electronProducer = cms.InputTag('electrons'),
        #electronProducer = cms.InputTag('pixelMatchGsfElectrons'),
        IsolationProducer = cms.InputTag('eleIsoFromDepsEcalFromHits'),
        isoCutEB = cms.double(5.7),
        isoCutEE = cms.double(5.0),
        EBEEBound = cms.double(1.5)
)

theIsolation = cms.EDProducer("IsolatedElectronCandProducer",
        electronProducer = cms.InputTag('theEcalIsolation'),
        #electronProducer = cms.InputTag('pixelMatchGsfElectrons'),
        IsolationProducer = cms.InputTag('eleIsoFromDepsHcalFromTowers'),
        isoCutEB = cms.double(8.1),
        isoCutEE = cms.double(3.4),
        EBEEBound = cms.double(1.5)
)

# Cut-based Robust electron ID  ######
from RecoEgamma.ElectronIdentification.electronIdCutBasedExt_cfi import *
import RecoEgamma.ElectronIdentification.electronIdCutBasedExt_cfi
eidRobust = RecoEgamma.ElectronIdentification.electronIdCutBasedExt_cfi.eidCutBasedExt.clone()
eidRobust.src = cms.InputTag('theIsolation')
eidRobust.robustEleIDCuts = cms.PSet(
            barrel = cms.vdouble(999.9, 0.010, 999.9, 0.0071),
            endcap = cms.vdouble(999.9, 0.028, 999.9, 0.0066)
                )

eidRobust.looseEleIDCuts = cms.PSet(
        invEMinusInvP = cms.vdouble(0.02, 0.02, 0.02, 0.02, 0.02,
            0.02, 0.02, 0.02, 0.02),
        EoverPInMin = cms.vdouble(0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0),
        EoverPOutMin = cms.vdouble(0.7, 1.7, 0.9, 0.6, 0.7,
            1.7, 0.9, 0.6, 0.5),
        sigmaEtaEtaMin = cms.vdouble(0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0),
        EoverPOutMax = cms.vdouble(2.5, 999.0, 2.2, 999.0, 2.5,
            999.0, 2.2, 999.0, 999.0),
        EoverPInMax = cms.vdouble(999.0, 999.0, 999.0, 999.0, 999.0,
            999.0, 999.0, 999.0, 999.0),
        deltaPhiOut = cms.vdouble(0.011, 999.0, 999.0, 999.0, 0.02,
            999.0, 999.0, 999.0, 999.0),
        sigmaEtaEtaMax = cms.vdouble(0.010, 0.010, 0.010, 0.010, 0.010,
            0.028, 0.028, 0.028, 0.028),
        deltaPhiIn = cms.vdouble(0.02, 0.06, 0.06, 0.08, 0.02,
            0.06, 0.06, 0.08, 0.08),
        HoverE = cms.vdouble(0.06, 0.06, 0.07, 0.08, 0.06,
            0.06, 0.07, 0.08, 0.12),
        sigmaPhiPhiMin = cms.vdouble(0.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 0.0),
        bremFraction = cms.vdouble(0.2, 0.2, 0.2, 0.2, 0.2,
            0.2, 0.2, 0.2, 0.2),
        deltaEtaIn = cms.vdouble(0.0071, 0.0071, 0.0071, 0.0071, 0.0071,
            0.0066, 0.0066, 0.0066, 0.0066),
        E9overE25 = cms.vdouble(0.8, 0.7, 0.7, 0.5, 0.8,
            0.8, 0.8, 0.8, 0.5),
        sigmaPhiPhiMax = cms.vdouble(999.0, 999.0, 999.0, 999.0, 999.0,
            999.0, 999.0, 999.0, 999.0)
    )
eidRobust.useEoverPOut = cms.vint32(0, 0, 0)
eidRobust.useHoverE = cms.vint32(0, 0, 0)
eidRobust.useE9overE25 = cms.vint32(0, 0, 0)
eidRobust.useDeltaEtaIn = cms.vint32(1, 1, 1)
eidRobust.useDeltaPhiIn = cms.vint32(0, 0, 0)
eidRobust.useDeltaPhiOut = cms.vint32(0, 0, 0)
eidRobust.useSigmaEtaEta = cms.vint32(1, 1, 1)

theId = cms.EDProducer("eidCandProducer",
    electronCollection = cms.untracked.InputTag('theIsolation'),
    electronLabelLoose = cms.InputTag('eidRobust')
)

# Trigger  ##################
theHLT = cms.EDProducer("eTriggerCandProducer",
    InputProducer = cms.InputTag('theId'),
    #hltTag = cms.untracked.InputTag("hltL1NonIsoHLTNonIsoSingleElectronEt10TrackIsolFilter","","HLT")
    hltTag = cms.untracked.InputTag("hltL1NonIsoHLTLooseIsoSingleElectronLWEt15TrackIsolFilter","","HLT")
    ##hltTag = cms.untracked.InputTag("hltL1NonIsoHLTNonIsoSingleElectronLWEt15TrackIsolFilter","","HLT")
)

theHLTInc = cms.EDProducer("eTriggerCandProducer",
    InputProducer = cms.InputTag('pixelMatchGsfElectrons'),
    #hltTag = cms.untracked.InputTag("hltL1NonIsoHLTNonIsoSingleElectronEt10TrackIsolFilter","","HLT")
    hltTag = cms.untracked.InputTag("hltL1NonIsoHLTLooseIsoSingleElectronLWEt15TrackIsolFilter","","HLT")
    ##hltTag = cms.untracked.InputTag("hltL1NonIsoHLTNonIsoSingleElectronLWEt15TrackIsolFilter","","HLT")
)

tpMapEnd = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(110.0),
    TagCollection = cms.InputTag("theHLT"),
    MassMinCut = cms.untracked.double(70.0),
    ProbeCollection = cms.InputTag("theId"),
    RequireOS = cms.untracked.bool(False)
)

#electron_sequence = cms.Sequence(electrons * theGsfElectrons * theGsfHf * theIsolation * eidRobust * theId * theHLT * HFElectronID )

electron_sequence = cms.Sequence(electrons * theGsfElectrons * theGsfHf * theGsfM1 * theGsfM2 * theGsfM3 * theGsfM4 * theGsfEE * theGsfRap * eleIsoDepositTk * eleIsoFromDepsTk * theTrackerIsolation * eleIsoDepositEcalFromHits * eleIsoFromDepsEcalFromHits * theEcalIsolation * eleIsoDepositHcalFromTowers * eleIsoFromDepsHcalFromTowers * theIsolation  * eidRobust * theId * theHLT * theHLTInc * HFElectronID * tpMapEnd )

    ################################################################
    ############  All Tag / Probe Association Maps  ###############
    ################################################################
    #// Remember that tag will always be "theHLT" collection.
    #//
    #// Probe can be one of the following collections:
    #// "theSuperClusters", "theGsfElectrons", "theIsolation", "theId".
    #//
    #// Passing Probe can be one of the following collections:
    #// "theGsfElectrons", "theIsolation", "theId", "theHLT".
    #//

tpMapSuperClusters = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(120.0),
    #TagCollection = cms.InputTag("theHLT"),
    TagCollection = cms.InputTag("theSuperClusters"),
    MassMinCut = cms.untracked.double(60.0),
    ProbeCollection = cms.InputTag("theSuperClusters")
)

tpMappreSuperClusters = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(130.0),
    TagCollection = cms.InputTag("theHLT"),
    MassMinCut = cms.untracked.double(50.0),
    ProbeCollection = cms.InputTag("thepreSuperClusters")
)

tpMapGsfElectrons = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(120.0),
    #TagCollection = cms.InputTag("theHLT"),
    TagCollection = cms.InputTag("theGsfElectrons"),
    MassMinCut = cms.untracked.double(60.0),
    ProbeCollection = cms.InputTag("theGsfElectrons")
)

tpMapIsolation = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(120.0),
    TagCollection = cms.InputTag("theHLT"),
    MassMinCut = cms.untracked.double(60.0),
    ProbeCollection = cms.InputTag("theIsolation")
)

tpMapId = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(120.0),
    TagCollection = cms.InputTag("theHLT"),
    MassMinCut = cms.untracked.double(60.0),
    ProbeCollection = cms.InputTag("theId")
)

tpMapHFSuperClusters = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(120.0),
    TagCollection = cms.InputTag("theHLT"),          #theID??
    MassMinCut = cms.untracked.double(60.0),
    ProbeCollection = cms.InputTag("theHFSuperClusters")
)

tpMapGsfAndHF = cms.EDProducer("TagProbeProducer",
    MassMaxCut = cms.untracked.double(120.0),
    TagCollection = cms.InputTag("theHLT"),          #theID??
    MassMinCut = cms.untracked.double(60.0),
    ProbeCollection = cms.InputTag("theGsfHf")
)

tpMap_sequence = cms.Sequence(tpMappreSuperClusters + tpMapSuperClusters + tpMapGsfElectrons + tpMapIsolation + tpMapId + tpMapHFSuperClusters + tpMapGsfAndHF)

    ################################################################
    ############  All Truth-matched collections  ###################
    ################################################################
    #// find generator particles matching by DeltaR

preSuperClustersMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("thepreSuperClusters"),
    distMin = cms.double(0.1),
    matched = cms.InputTag("genParticles")
)

SuperClustersMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("theSuperClusters"),
    distMin = cms.double(0.3),
    matched = cms.InputTag("genParticles")
)

GsfElectronsMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("theGsfElectrons"),
    distMin = cms.double(0.3),
    matched = cms.InputTag("genParticles")
)

IsolationMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("theIsolation"),
    distMin = cms.double(0.3),
    matched = cms.InputTag("genParticles")
)

IdMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("theId"),
    distMin = cms.double(0.3),
    matched = cms.InputTag("genParticles")
)

HLTMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("theHLT"),
    distMin = cms.double(0.3),
    matched = cms.InputTag("genParticles")
)

HFSCMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("theHFSuperClusters"),
    distMin = cms.double(0.3),
    matched = cms.InputTag("genParticles")
)

HFIDMatch = cms.EDFilter("MCTruthDeltaRMatcherNew",
    pdgId = cms.vint32(11),
    src = cms.InputTag("HFElectronID"),
    distMin = cms.double(0.3),
    matched = cms.InputTag("genParticles")
)

truthMatch_sequence = cms.Sequence(preSuperClustersMatch + SuperClustersMatch + GsfElectronsMatch + IsolationMatch + IdMatch + HLTMatch + HFSCMatch + HFIDMatch)

#lepton_cands = cms.Sequence(genParticles * hfEMClusteringSequence * sc_sequence * electron_sequence * tpMap_sequence * truthMatch_sequence)
#lepton_cands = cms.Sequence(genParticles *  ZIntoElectronsEventProducer * SmearedElectronsProducer * hfEMClusteringSequence * sc_sequence * electrons * theGsfElectrons)
lepton_cands = cms.Sequence(genParticles * hfEMClusteringSequence * sc_sequence * electrons * theGsfElectrons)


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

# Copyright 2016 Resonai Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
yabt target graph
~~~~~~~~~~~~~~~~~

:author: Itamar Ostricher
"""

from collections import defaultdict
from os.path import relpath

import difflib
import networkx
from networkx.algorithms import dag

from .buildfile_parser import process_build_file
from .compat import walk
from .config import Config
from .logging import make_logger
from .target_utils import (
    norm_name, parse_target_selectors, split, split_build_module)

logger = make_logger(__name__)

def build_target_dep_graph(build_context, unused_conf: Config):
    build_context.target_graph = networkx.DiGraph()
    for target_name, target in build_context.targets.items():
        build_context.target_graph.add_node(target_name)
        for dep in target.deps:
            build_context.target_graph.add_edge(target_name, dep)

def norm_rel_target(target_spec, build_module):
    if ':' not in target_spec:
        target_spec += ':*'
    return norm_name(build_module, target_spec)

def generate_all_targets(conf: Config):
    # TODO(itamar): add ignore marker files / flags
    for root, unused_dirs, files in walk(conf.project_root):
        if conf.build_file_name in files:
            yield norm_rel_target(relpath(root, conf.project_root), '//')

class SeedRef:
    """Helper class for tracking references to targets.

    This class is used mainly for error reporting.
    A single instance represents a single target observed during build graph
    processing (AKA "seed"), in any context, whether valid or not (not
    including syntax error, which are caught and reported during YBuild
    parsing - see buildfile_parser module).

    Currently supprted contexts:
    - `on_cli` - whether this seed was specified on the command line (boolean).
    - `from_default` - whether this seed was specified as one of the "default"
      targets that seed the graph if nothing is specified on the command line.
    - `dep_of` - a set of other seeds that referred to this seed as their
      dependency.
    - `buildenv_of` - a set of other seeds that referred to this seed as their
      buildenv.

    Usage: Through a defaultdict of SeedRefs (mapping from seed name to its
    SeedRef instance) in populate_targets_graph - for every target processed,
    need to add the processed target to all the seeds that that target refers
    to (a reverse index).
    When an error is found, the raise_unresolved_targets function may use the
    mapping to report where an invalid seed was observed.
    """

    def __init__(self):
        self.on_cli = False
        self.from_default = False
        self.dep_of = set()
        self.buildenv_of = set()

def raise_unresolved_targets(build_context, conf, unknown_seeds, seed_refs):
    """Raise error about unresolved targets during graph parsing."""

    def format_target(target_name):
        # TODO: suggest similar known target names
        build_module = split_build_module(target_name)
        return '{} (in {})'.format(target_name,
                                   conf.get_build_file_path(build_module))

    def format_unresolved(seed):
        if seed not in seed_refs:
            return seed
        seed_ref = seed_refs[seed]
        reasons = []
        if seed_ref.on_cli:
            reasons.append('seen on command line')
        if seed_ref.from_default:
            reasons.append('specified as default target in {}'
                           .format(conf.get_project_build_file))
        if seed_ref.dep_of:
            reasons.append(
                'dependency of ' +
                ', '.join(format_target(target_name)
                          for target_name in sorted(seed_ref.dep_of)))
        if seed_ref.buildenv_of:
            reasons.append(
                'buildenv of ' +
                ', '.join(format_target(target_name)
                          for target_name in sorted(seed_ref.buildenv_of)))

        return '{} (possible misspelling of {}) - {}'.format(
            seed, difflib.get_close_matches(
                seed, build_context.targets.keys()), ', '.join(reasons))

    unresolved_str = '\n'.join(format_unresolved(target_name)
                               for target_name in sorted(unknown_seeds))
    num_target_str = '{} target'.format(len(unknown_seeds))
    if len(unknown_seeds) > 1:
        num_target_str += 's'
    raise ValueError('Could not resolve {}:\n{}'
                     .format(num_target_str, unresolved_str))

def populate_targets_graph(build_context, conf: Config):
    # Process project root build file
    process_build_file(conf.get_project_build_file(), build_context, conf)
    targets_to_prune = set(build_context.targets.keys())
    seed_refs = defaultdict(SeedRef)
    if conf.targets:
        logger.debug('targets: {}', conf.targets)
        # TODO(itamar): Figure out how to support a target selector that is a
        #   parent directory which isn't a build module, but contains build
        #   modules (e.g., `ybt tree yapi` from the `dag` test root).
        seeds = parse_target_selectors(conf.targets, conf)
        logger.debug('seeds: {}', seeds)
        for cli_seed in seeds:
            seed_refs[cli_seed].on_cli = True
    else:
        default_target = ':{}'.format(conf.default_target_name)
        logger.info('searching for default target {}', default_target)
        if default_target not in build_context.targets:
            raise RuntimeError(
                'No default target found in {}, and no target selector '
                'specified'.format(conf.get_project_build_file()))
        seeds = [default_target]
        seed_refs[default_target].from_default = True

    def extend_seeds(target_name):
        target = build_context.targets[target_name]
        seeds.extend(target.deps)
        for dep in target.deps:
            seed_refs[dep].dep_of.add(target_name)
        if target.buildenv:
            seeds.append(target.buildenv)
            seed_refs[target.buildenv].buildenv_of.add(target_name)

    # Crawl rest of project from seeds
    seeds_used_for_extending = set()
    unknown_seeds = set()
    for seed in seeds:
        if seed in build_context.targets:
            #
            if seed in targets_to_prune:
                targets_to_prune.remove(seed)
            if seed not in seeds_used_for_extending:
                # Avoid infinite loop in case of cyclic dependencies
                extend_seeds(seed)
                seeds_used_for_extending.add(seed)
        else:
            if seed == '**:*':
                # Adding all build modules under current working directory as
                # seeds
                seeds.extend(generate_all_targets(conf))
                continue
            build_module, target_name = split(seed)
            process_build_file(conf.get_build_file_path(build_module),
                               build_context, conf)
            # Parsed build file with this seed target - add its dependencies as
            # seeds
            if target_name == '*':
                # It's a wildcard - add all targets from build module
                # (and skip adding to targets_to_prune altogether)
                for module_target in (
                        build_context.targets_by_module[build_module]):
                    extend_seeds(module_target)
            else:
                if seed not in build_context.targets:
                    unknown_seeds.add(seed)
                    continue
                for module_target in (
                        build_context.targets_by_module[build_module]):
                    targets_to_prune.add(module_target)
                targets_to_prune.remove(seed)
                extend_seeds(seed)
        # TODO(itamar): Write tests that pruning is *ALWAYS* correct!
        # e.g., not pruning things it shouldn't (like when targets are in prune
        # list when loaded initially, but should be removed later because a
        # target loaded later required them).

    if unknown_seeds:
        raise_unresolved_targets(build_context, conf, unknown_seeds, seed_refs)

    # Pruning, after parsing is done
    # (first, adding targets that are tagged as "prune-me" to prune list)
    targets_to_prune.update(
        target_name
        for target_name, target in build_context.targets.items()
        if 'prune-me' in target.tags)
    for target_name in targets_to_prune:
        build_context.remove_target(target_name)

    # fill in an actual target graph using the dependencies info
    # and assert that it has no cycles
    build_target_dep_graph(build_context, conf)
    if not dag.is_directed_acyclic_graph(build_context.target_graph):
        cycles = '\n'.join(
            ' -> '.join(cycle)
            for cycle in networkx.simple_cycles(build_context.target_graph))
        raise RuntimeError('Detected cycles in build graph!\n' + cycles)

    # go over the graph and assert policies
    violations = []
    if conf.policies:
        for target in build_context.targets.values():
            for policy in conf.policies:
                err = policy(build_context, target)
                if err:
                    violations.append(
                        '- Target {} violates {} policy: {}'.format(
                            target.name, policy.__name__, err))
    if violations:
        raise RuntimeError('Policy violations:\n' + '\n'.join(violations))

    logger.info('Finished parsing build graph with {} nodes and {} edges',
                build_context.target_graph.order(),
                build_context.target_graph.size())

def top_rev_sort_subgraph_stable(graph):
    """
    This is a  topological sorting algorithm stable for all subgraphs
    L <- Empty queue that will contain the sorted elements
    S <- Set of all nodes with no outcoming edges

    while S is non-empty do
    remove a node n from S
    add n to tail of L
    for each node m with an edge e from n to m do
        remove edge e from the graph
        if m has no other outcoming edges then
        insert m into S

    if graph has edges then
    return error     (graph has at least one cycle)
    else
    return L     (a topologically sorted order)
    """
    if not graph.is_directed():
        raise networkx.NetworkXError(
            'Topological sort not defined on undirected graphs.')
    graph = graph.copy()
    visited = dict.fromkeys(graph.nodes(), False)
    while True:
        set_s = []
        for node in graph.nodes():
            if not visited[node]:
                if graph.out_degree(node) == 0:
                    visited[node] = True
                    set_s.append(node)
        set_s.sort()
        if not set_s:
            break
        for node in set_s:
            yield node
            graph.remove_node(node)
    if graph:
        raise networkx.NetworkXUnfeasible('Graph contains a cycle.')

def topological_sort(graph: networkx.DiGraph):
    yield from top_rev_sort_subgraph_stable(graph)

def get_descendants(graph: networkx.DiGraph, source):
    """Return all nodes reachable from `source` in `graph`."""
    return dag.descendants(graph, source)

def get_ancestors(graph: networkx.DiGraph, child):
    """Return all nodes that have 'child' as a descendant in 'graph'"""
    return dag.ancestors(graph, child)

def get_graph_roots(graph):
    for id_deg in graph.in_degree():
        if id_deg[1] == 0:
            yield id_deg[0]

def cut_from_graph(graph, name):
    graph = graph.copy()
    cut_s = {name}
    cut_s.update(dag.descendants(graph, name))
    nodes = list(graph.nodes())
    for node in nodes:
        if node not in cut_s:
            graph.remove_node(node)
    return graph


# coding=utf-8
import cv2
from PIL import Image
import model
import os
import re
from aijian_project.extract_front import extract_front,read_data
from aijian_project.extract_reverse import extract_reverse_csv
from aijian_project.utils import extract_number,extract_address,extract_nation,extract_name,extract_department,extract_date
import xlwt
import xlrd
import openpyxl
import sys
import csv
from time import time

# aaa = "C:/Users\EDZ\Desktop/test_idcard"
# aaa = "C:/Users\EDZ\Desktop/ID_card"

def main(aaa,save_path,flag):
    # aaa =  "/root/datatom/front1.xls"
    # save_path = "/root/datatom/front1_res.xls"
    # flag = "front"

    csv_data = csv.reader(open(aaa, "r", encoding="GBK"))
    total =0
    if os.path.exists(save_path):
        with open(save_path, "r", encoding="GBK") as f:
            tmp_data = csv.reader(f)
            for tmp in tmp_data:
                total = int(tmp[0])
            f.close()
    print("total ran datas:",total)
    # writer = csv.writer(open(save_path, "w", encoding="GBK"), lineterminator="\n")

    for numi,i in enumerate(csv_data):
        if int(i[0]) <= total:
            continue
        start = time()
        image_path = i[5][3:]
        print("run ",str(numi)," ",i[0]," ",image_path)
        try:
            img = cv2.imread(image_path)
        except:
            continue
        try:
            if len(img)== 0:
                continue
        except Exception as e:
            print("len(img) error! ",e)
            continue
        try:
            h,w =img.shape[:2]
        except Exception as e:
            print("img.shape error! ",e)
            continue
        try:
            _, result, angle = model.model(img,
                                       detectAngle=False,  ##是否进行文字方向检测
                                       config=dict(MAX_HORIZONTAL_GAP=50,  ##字符之间的最大间隔，用于文本行的合并
                                                   MIN_V_OVERLAPS=0.6,
                                                   MIN_SIZE_SIM=0.6,
                                                   TEXT_PROPOSALS_MIN_SCORE=0.1,
                                                   TEXT_PROPOSALS_NMS_THRESH=0.3,
                                                   TEXT_LINE_NMS_THRESH=0.7,  ##文本行之间测iou值

                                                   ),
                                       leftAdjust=True,  ##对检测的文本行进行向左延伸
                                       rightAdjust=True,  ##对检测的文本行进行向右延伸
                                       alph=0.01,  ##对检测的文本行进行向右、左延伸的倍数
                                       )
        except Exception as e:
            print("model.model error！",e)
            continue

        # print(result)
        # with open("./result_all_"+flag+".txt","a+") as f:
        #     f.write(image_path + "\n")
        #     for line in result:
        #         # print(line["text"])
        #         f.write(line["text"]+"\n")
        #     f.write("\n")

        with open(save_path, "a+", encoding="GBK") as f:
            writer = csv.writer(f, lineterminator="\n")
            if flag == "reverse":
                data = {}
                date = extract_date(result)
                department = extract_department(result)
                data["date"] = date
                data["department"] = department
                extract_reverse_csv(writer,i,data)
                print(data)

            else:
                data = {}
                name = extract_name(result)
                nation = extract_nation(result)
                address = extract_address(result)
                number = extract_number(result)
                data["name"] = name
                data["nation"] = nation
                data["address"] = address
                data["number"] = number
                extract_reverse_csv(writer,i,data)
                print(data)
            f.close()
        print("one image time:",time()-start)

if __name__ == '__main__':

    aaa = "/root/datatom/IDcard_28w.csv"
    save_path = "/root/datatom/IDcard_28w_reverse_res.csv"
    flag = "reverse"
    main(aaa, save_path, flag)

    # aaa = "/root/datatom/front_A1.csv"
    # save_path = "/root/datatom/front_A1_res.csv"
    # flag = "front"
    # main(aaa, save_path, flag)


from pydatapack import implementations
from pydatapack import snippets
from pydatapack import debug
from pydatapack import *

dp = Datapack('Diamond Duplication','Duplicate blocks using diamonds and item frames!')

dup = dp.newFunction('duplicate')
dup.addCommand('setblock ^ ^ ^1 minecraft:air destroy')
dup.addCommand('clone ~ ~ ~ ~ ~ ~ ^ ^ ^1')
dup.addCommand('particle minecraft:dust 0.1 1.0 1.0 2.0 ^ ^ ^1.5 0.3 0.3 0.3 10 100 force')
dup.addCommand('playsound minecraft:entity.experience_orb.pickup master @a[distance=..10] ~ ~ ~ 1 1')
dup.addCommand('kill @s')

for block in ['minecraft:chest','minecraft:trapped_chest']:
    dp.tick_function.addCommand(snippets.item_frame_connected_block('minecraft:diamond',dup(),item_rotation=-1,on_block=block))

dp.compile()


import json
import datetime
import itertools

import requests
from datapackage_pipelines.wrapper import ingest, spew

from datapackage_pipelines_measure.config import settings

import logging
log = logging.getLogger(__name__)

parameters, datapackage, res_iter = ingest()

name = str(parameters['name'])
repo = parameters.get('repo')
repo_url = '{}{}?access_token={}'.format(settings['GITHUB_API_BASE_URL'],
                                         repo,
                                         settings['GITHUB_API_TOKEN'])

try:
    repo_content = requests.get(repo_url).json()
except json.decoder.JSONDecodeError:
    log.error('Expected JSON in response from: {}'.format(repo_url))
    raise

resource_content = []
# remap retrieved dict to scheme in parameters
row = {t_key: repo_content[s_key]
       for t_key, s_key in parameters['map_fields'].items()}
row['source'] = 'github'
row['date'] = datetime.date.today()

resource = {
    'name': name,
    'path': 'data/{}.csv'.format(name)
}

# Temporarily set all types to string, will use `set_types` processor in
# pipeline to assign correct types
resource['schema'] = {
    'fields': [{'name': h, 'type': 'string'} for h in row.keys()]}

datapackage['resources'].append(resource)

resource_content.append(row)

spew(datapackage, itertools.chain(res_iter, [resource_content]))


import sys
import subword_text_tokenizer

## Usage: python encode_ste.py < train.txt > train.ste.txt

if len(sys.argv) != 2:
  raise RuntimeError("SubwordTextTokenizer vocab file's not found")
encoder = subword_text_tokenizer.SubwordTextTokenizer(sys.argv[1])

for line in sys.stdin:
  print(encoder.encode(line.strip()))


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

__all__ = ['_', 'C_', 'ngettext']

program = 'radiotray'

import locale
LC_ALL = locale.setlocale(locale.LC_ALL, '')

try:
    import gettext
    from gettext import gettext as _, ngettext
    gettext.install(program, unicode=True)
    gettext.textdomain(program)
    locale.textdomain(program)

    def C_(ctx, s):
        """Provide qualified translatable strings via context.
            Taken from gnome-games.
        """
        translated = gettext.gettext('%s\x04%s' % (ctx, s))
        if '\x04' in translated:
            # no translation found, return input string
            return s
        return translated
    import __builtin__
    __builtin__.__dict__['ngettext'] = ngettext
    __builtin__.__dict__['C_'] = C_
except ImportError:
    import sys
    print >> sys.stderr, ("You don't have gettext module, no " \
        "internationalization will be used.")
    import __builtin__
    __builtin__.__dict__['_'] = lambda x: x
    __builtin__.__dict__['ngettext'] = lambda x, y, n: (n == 1) and x or y


from marketsim import registry
from marketsim.gen._out._observable import Observablefloat
from marketsim.gen._intrinsic.observable.on_every_dt import _OnEveryDt_Impl
from marketsim.gen._out._ifunction import IFunctionfloat
@registry.expose(["Basic", "OnEveryDt"])
class OnEveryDt_FloatFloat(Observablefloat,_OnEveryDt_Impl):
    """
    """
    def __init__(self, x = None, dt = None):
        from marketsim.gen._out._observable import Observablefloat
        from marketsim.gen._out._constant import constant_Float as _constant_Float
        from marketsim import rtti
        Observablefloat.__init__(self)
        self.x = x if x is not None else _constant_Float(1.0)

        self.dt = dt if dt is not None else 1.0

        rtti.check_fields(self)
        _OnEveryDt_Impl.__init__(self)

    @property
    def label(self):
        return repr(self)

    _properties = {
        'x' : IFunctionfloat,
        'dt' : float
    }
    def __repr__(self):
        return "[%(x)s]_dt=%(dt)s" % self.__dict__

def OnEveryDt(x = None,dt = None):
    from marketsim.gen._out._ifunction import IFunctionfloat
    from marketsim import rtti
    if x is None or rtti.can_be_casted(x, IFunctionfloat):
        if dt is None or rtti.can_be_casted(dt, float):
            return OnEveryDt_FloatFloat(x,dt)
    raise Exception('Cannot find suitable overload for OnEveryDt('+str(x) +':'+ str(type(x))+','+str(dt) +':'+ str(type(dt))+')')


# -*- coding: utf-8 -*-
"""
:Author: Jaekyoung Kim
:Date: 2019-01-07
"""
import numpy as np
import pandas as pd
from ksif.core.columns import *

RET = 'return'
YYYYMM = 'year_month'

if __name__ == '__main__':
    method = 'Intersection'
    model_name = 'DNN8_1-all-linear-he_uniform-glorot_uniform-none-0.5'

    monthly_portfolio = pd.read_csv('data/portfolio.csv', parse_dates=[DATE])
    monthly_portfolio[DATE] += np.timedelta64(1, 'D')
    monthly_portfolio[YYYYMM] = monthly_portfolio[DATE].dt.year.astype(str) + \
                                monthly_portfolio[DATE].dt.month.astype(str).str.zfill(2)
    monthly_portfolio = monthly_portfolio[[CODE, YYYYMM]]

    daily_adjp = pd.read_csv('data/daily_adjp.csv', parse_dates=[DATE])
    daily_adjp.set_index([DATE], inplace=True)

    daily_returns = daily_adjp.pct_change(fill_method='ffill')
    daily_returns.reset_index(drop=False, inplace=True)
    daily_returns = pd.melt(daily_returns, id_vars=[DATE], var_name=CODE, value_name=RET)
    daily_returns.dropna(inplace=True)
    daily_returns[YYYYMM] = daily_returns[DATE].dt.year.astype(str) + \
                            daily_returns[DATE].dt.month.astype(str).str.zfill(2)

    daily_portfolio = pd.merge(monthly_portfolio, daily_returns, on=[CODE, YYYYMM])[[DATE, RET]]
    daily_returns = daily_portfolio.groupby(DATE).mean()
    daily_returns.to_csv('daily_backtest/{}-{}.csv'.format(method, model_name))


from sqlalchemy.orm import Session
from crud import crud_channel_manager,crud_shop
from models import channel
from schemas import channel_schema

def get_channel(db: Session, channel_id: str):
    return db.query(channel.Channel).filter(channel.Channel.id == channel_id).first()

def get_all_channel(db: Session, skip: int = 0, limit: int = 100):
    channels= db.query(channel.Channel).offset(skip).limit(limit).all()
    for c in channels:
        c.number_of_manager=crud_channel_manager.count_manager_of_channel(db=db,channel_id=c.id)
        c.number_of_shop=crud_shop.count_shop(db=db,channel_id=c.id)
    return channels
def get_all_channel_db(db: Session):
    channels=db.query(channel.Channel).all()
    for c in channels:
        c.number_of_manager=crud_channel_manager.count_manager_of_channel(db=db,channel_id=c.id)
        c.number_of_shop=crud_shop.count_shop(db=db,channel_id=c.id)
    return channels

def create_channel(db: Session, created_channel: channel_schema.ChannelCreate):
    db_channel = channel.Channel(id=created_channel.id,name=created_channel.name)
    db.add(db_channel)
    db.commit()
    db.refresh(db_channel)
    return db_channel

def get_all_channel_of_manager(db:Session,manager_id:str):
    all_channel_id=[]
    for id in crud_channel_manager.get_channel_id_of_manager(db=db,manager_id=manager_id):
        all_channel_id.append(id[0])

    return db.query(channel.Channel).filter(channel.Channel.id.in_(all_channel_id)).all()

def get_all_not_channel_of_manager(db:Session,manager_id:str):
    all_channel_id=[]
    for id in crud_channel_manager.get_channel_id_of_manager(db=db,manager_id=manager_id):
        all_channel_id.append(id[0])

    return db.query(channel.Channel).filter(channel.Channel.id.notin_(all_channel_id)).all()


from __future__ import division

T = int(raw_input())

for t in xrange(1, T+1):
    D = raw_input()
    arr = map(int, raw_input().split())
    highest = max(arr)

    res = highest

    for max_stack in xrange(1, highest):
        splits = 0
        for i in arr:
            while i > max_stack:
                i -= max_stack
                splits += 1
        res = min(res, splits + max_stack)

    print("Case #{}: {}".format(t, res))


from __future__ import print_function
import time

PITCH_CONTROL_TOLERANCE = 4.0
PITCH_TARGET_TOLERANCE = 2.0

class PID:
    """PID Controller"""

    def __init__(self, motor_controller, target, control_tolerance, target_tolerance, debug, p=0.2, i=0.0, d=0.0, i_windup=20.0):
        # Initialize parameters
        self.mc = motor_controller
        self.set_point = target
        self.control_tolerance = control_tolerance
        self.target_tolerance = target_tolerance
        self.p = p
        self.i = i
        self.d = d
        self.windup = i_windup
        self.is_debug = debug
        self.last_error = 0.0
        self.sum_error = 0.0
        self.last_time = time.time()
        self.within_tolerance = False

    def pid(self, current_value):
        """PID Calculation"""
        # Calculate error
        #error = self.set_point - current_value
        abs_error = self.set_point - current_value
        if(abs_error < 180):
            error = abs_error
        else:
            error = abs_error - 360

        # Figure out state
        if(self.within_tolerance and abs(error) > self.control_tolerance):
            self.within_tolerance = False
        elif(not self.within_tolerance and abs(error) < self.target_tolerance):
            self.within_tolerance = True

        # PID
        if(self.within_tolerance):
            if(self.is_debug):
                #print("PID inside tolerance")
                print('[PID]In Target %7.2f Current %7.2f Error %7.2f' % (self.set_point, current_value, error), end='\r')

            return 0

        dt = time.time() - self.last_time

        # Calculate P term
        p_term = self.p * error
        # Calculate I term
        self.sum_error += error * (time.time() - self.last_time)
        i_change = self.sum_error if abs(self.sum_error) < self.windup else (
            self.windup if self.sum_error >= 0 else -self.windup)
        i_change *= dt
        i_term = self.i * i_change
        # Calculate D term
        d_term = self.d * (error - self.last_error)
        d_term /= dt

        # Update values for next iteration
        self.last_time = time.time()
        self.last_error = error
        if(self.is_debug):
            print('[PID]SetPoint %7.2f Current %7.2f Error %7.2f P %7.2f I %7.2f D %7.2f Feedback %7.2f' %
                                      (self.set_point, current_value, error, p_term, i_term, d_term, p_term+i_term+d_term), end='\t')
        return p_term + i_term + d_term  # pid

    def pid_pitch(self, current_value):
        """PID Calculation"""
        # Calculate error
        error = current_value
        # Figure out state

        if(self.within_tolerance and abs(error) > self.control_tolerance ):
            print("Not within tolerance")
            self.within_tolerance = False
        elif(not self.within_tolerance and abs(error) < self.target_tolerance):
            print("Within tolerance")
            self.within_tolerance = True

        # PID
        if(self.within_tolerance):
            if(self.is_debug):
                #print("PID inside tolerance")
                print('[PID]In Target %7.2f Current %7.2f Error %7.2f' % (self.set_point, current_value, error), end='\r')

            return 0

        dt = time.time() - self.last_time

        # Calculate P term
        p_term = self.p * error
        # Calculate I term
        self.sum_error += error * (time.time() - self.last_time)
        i_change = self.sum_error if abs(self.sum_error) < self.windup else (
            self.windup if self.sum_error >= 0 else -self.windup)
        i_change *= dt
        i_term = self.i * i_change
        # Calculate D term
        d_term = self.d * (error - self.last_error)
        d_term /= dt

        # Update values for next iteration
        self.last_time = time.time()
        self.last_error = error
        if(self.is_debug):
            print('[PID]SetPoint %7.2f Current %7.2f Error %7.2f P %7.2f I %7.2f D %7.2f Feedback %7.2f' %
                                      (0, current_value, error, p_term, i_term, d_term, p_term+i_term+d_term), end='\t')
        return p_term + i_term + d_term

    def set_p(self, p):
        self.p = p

    def set_i(self, i):
        self.i = i

    def set_d(self, d):
        self.d = d

    def set_windup(self, windup):
        """Integral windup, also known as integrator windup or reset windup,
        refers to the situation in a PID feedback controller where
        a large change in setpoint occurs (say a positive change)
        and the integral terms accumulates a significant error
        during the rise (windup), thus overshooting and continuing
        to increase as this accumulated error is unwound
        (offset by errors in the other direction).
        The specific problem is the excess overshooting.
        """
        self.windup = windup

    def update_target(self, target):
        self.set_point = target


"""
https://leetcode.com/problems/fizz-buzz/
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and
for the multiples of five output “Buzz”. For numbers which are multiples of
both three and five output “FizzBuzz”.
"""

def main():
    n = 30
    res = fizzbuzz(n)
    for i in res:
        print(i)

def fizzbuzz(n):

    r =[]

    for i in range(1, n+1):

        div_by_3 = (i % 3 == 0)
        div_by_5 = (i % 5 == 0)

        if div_by_3 and div_by_5:
            r.append('FizzBuzz')
        elif div_by_3:
            r.append('Fizz')
        elif div_by_5:
            r.append('Buzz')
        else:
            r.append(str(i))
    return r

if __name__ == "__main__":
    main()


from nhl_py.http import NHLHTTP

class Standings:
    endpoint = 'standings'
    data = None

    def __init__(self, season=None, date=None):
        """
        Returns NHL standings
        Parameters
        ----------
        season : int
            The season of the standings you want. Example: 20032004 for the 2003-2004 season.
        date : str
            To retrieve the standings on a specific date. Example: '2018-01-09'
        """
        http = NHLHTTP()
        endpoint = self.endpoint
        query_str = False
        if season != None:
            endpoint += '?season=' + season
            query_str = True
        if date != None:
            if query_str:
                endpoint += '&date=' + date
            else:
                endpoint += '?date=' + date

        self.data = http.send_api_request(endpoint)


# coding: utf-8

# In[17]:

import pandas as pd

# In[18]:

print('\t\tWelcome To our Airport Management System ')

# In[19]:

data1=pd.read_csv(r'new.csv')

# In[20]:

data1.sort_values(['AIRLINE_NAME'], axis = 0, ascending = [True], inplace = True, na_position ='last')
q=input('Enter Airline name : ')

# In[21]:

data1.sort_values(["ORIGIN",'DEST'], axis = 0, ascending = [True,True], inplace = True, na_position ='last')

# In[22]:

a=input("Enter The City From Where U Want To Start The Journey : ")

# In[8]:

#data1.head()

# In[23]:

b=input("Enter The City  Where U Want To End The Journey : ")

# In[24]:

#for a in data1

# In[25]:

if (data1.loc[(data1['ORIGIN']==a)&(data1['DEST']==b)].sum)==0:
      print("NO FLIGHTS AVAILABLE \t")
else:
    print("\tThe Schedule Is\t")

# In[26]:

b=data1.loc[(data1['ORIGIN']==a)&(data1['DEST']==b)]

# In[28]:

print(b)

# In[29]:

print("\n\t\tIf We Sort On The Basis Of Time The Schedule Will be ")

# In[30]:

b.sort_values(["AIR_TIME"], axis = 0, ascending = [True], inplace = True, na_position ='last')

# In[32]:

#print("\t\tThe schedule is")
print(b)

# In[ ]:


from copy import deepcopy
from functools import partial

from aiohttp import web
from aiohttp_session import get_session

SESSION_KEY = REQUEST_KEY = 'flash'

def flash(request, message):
  request[REQUEST_KEY].append(message)

def pop_flash(request):
  flash = request[REQUEST_KEY]
  request[REQUEST_KEY] = []
  return flash

@web.middleware
async def flash_middleware(request, handler):
  session = await get_session(request)
  flash_incoming = session.get(SESSION_KEY, [])
  request[REQUEST_KEY] = deepcopy(
      flash_incoming)  # copy flash for modification
  try:
    response = await handler(request)
  finally:
    flash_outgoing = request[REQUEST_KEY]
    if flash_outgoing != flash_incoming:
      if flash_outgoing:
        session[SESSION_KEY] = flash_outgoing
      else:
        del session[SESSION_KEY]
  return response

async def context_processor(request):
  return {
      'get_flashed_messages': partial(pop_flash, request),
  }


import torch
import timeit
dtype = torch.float
if torch.cuda.is_available():
    device = torch.device("cuda")
else:
    device = torch.device("cpu")

start = timeit.default_timer()

N, D_in, H, D_out = 64, 1000, 100, 10

x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)

w1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True)
w2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True)

learning_rate = 1e-6

for t in range(5000):
    y_pred = x.mm(w1).clamp(min=0).mm(w2)
    loss = (y_pred - y).pow(2).sum()
    if t % 100 > 90:
        print(t, loss.item())
    loss.backward()
    with torch.no_grad():
        w1 -= learning_rate * w1.grad
        w2 -= learning_rate * w2.grad
        w1.grad.zero_()
        w2.grad.zero_()

stop = timeit.default_timer()
total_time = stop - start

print('Time:', total_time)


import sys

from django.http import HttpResponse
from apipkg import api_manager as api
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django import forms

from . import models

import json

def index(request):
    time = api.send_request('scheduler', 'clock/time')
    return HttpResponse("L'heure de la clock est %r" % time)

# Print HelloWorld
def helloWolrd(request):
    if request.method != "GET":
        return HttpResponse("Forbidden")
    print(request)
    return HttpResponse("Hello World ! :)\n")

# POST request - print payload
@csrf_exempt
def printJson(request):
    if request.method != "POST":
        return HttpResponse("Forbidden")
    jsonBody = json.loads(request.body)
    return HttpResponse(jsonBody["app_name"] + " : " + jsonBody["message"])

# Display form
def displayForm(request):
    info = api.send_request("gestion-paiement", "info")
    print(info)
    name = forms.TextInput(attrs={'size': 10, 'title': 'Your name'})
    return render(request, 'form.html')

# Search after validation button
def search(request):
    if request.method == 'POST':
        print(request.POST.get('textfield', None))
        return HttpResponse(request.POST.get('textfield', None))
    else:
        return render(request, 'form.html')

# Save from DB
def saveDB(request):
    models.Article.objects.create(nom='Apple', stock=1)
    return HttpResponse("Saved")

# Read from DB
def readDB(request):
    return HttpResponse(models.Article.objects.values_list())

# Clear DB
# def removeDB(request):
#     models.Article.objects.all().delete()
#     return HttpResponse("Models removed")


from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from event.models import CommentForm, Comment

def index(request):
    return HttpResponse("Event Page")

@login_required(login_url='/login') #Check login
def addcomment (request,id):
    url = request.META.get('HTTP_REFERER')
    if request.method=='POST':
        form=CommentForm(request.POST)
        if form.is_valid():
            current_user=request.user
            data=Comment()
            data.user_id=current_user.id
            data.event_id=id
            data.subject=form.cleaned_data['subject']
            data.comment = form.cleaned_data['comment']
            data.rate = form.cleaned_data['rate']
            data.ip=request.META.get('REMOTE_ADDR')
            data.save()
            messages.success(request,"Yorumunuz basarılı bir şekilde gönderildi. Teşekkür ederiz.")
            return HttpResponseRedirect(url)

    messages.warning(request, "Yorumunuz kaydedilmedi. Lütfen kontrol edip tekrar deneyiniz.")
    return HttpResponseRedirect(url)