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

#-----------------------------------------------------------------------
# PROGRAM: app_static.py
#-----------------------------------------------------------------------
# Version 0.8
# 7 June, 2020
# Dr Michael Taylor
# https://patternizer.github.io
# patternizer AT gmail DOT com
#-----------------------------------------------------------------------

# ========================================================================
# SETTINGS
# ========================================================================
run_smoother = True
run_forecast = True
run_plots = True
plot_intervention = True
plot_total_error = True
plot_raw_obs = True
plot_mcmc = True

#value = 'Bangladesh'
#value = 'Brazil'
#value = 'Greece'
#value = 'India'
#value = 'Iran'
#value = 'Italy'
#value = 'Mexico'
#value = 'Morocco'
#value = 'Peru'
#value = 'Russia'
#value = 'Spain'
#value = 'Saudi Arabia'
value = 'United Kingdom'
#value = 'US'

# FAILING:
#value = 'China'
#value = 'South Korea'
#value = 'North Korea'
# ========================================================================

import numpy as np
import scipy.stats as st
from scipy.stats.kde import gaussian_kde
import pandas as pd
import matplotlib.pyplot as plt
import subprocess
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import seaborn as sns; sns.set()

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
import plotly.figure_factory as ff
import plotly.express as px
from plotly.subplots import make_subplots
from flask import Flask
import os
from random import randint

# -----------------------------------------------------------------------------
def quantile(x,q):
    n = len(x)
    y = np.sort(x)
    return(np.interp(q, np.linspace(1/(2*n), (2*n-1)/(2*n), n), y))

def smoother(vec):
    newvec = np.ones(len(vec))
    weekly = np.zeros(7)
    for i in np.arange(0,7):
        dy = np.arange(0,int(np.ceil((len(vec)-i)/7)))
        weekly[i] = np.mean(vec[dy*7+i])
    weeklymean = np.mean(weekly)
    for i in np.arange(0,7):
        dy = np.arange(0,int(np.ceil((len(vec)-i)/7)))
        newvec[dy*7+i] = vec[dy*7+i]*np.mean(weekly)/weekly[i]
    return newvec

def nearest_power_of_10(n):
    x = int(10**np.ceil(np.log10(n)))
    return x

def update_status(dp,dl,df,value):
    # Handle inconsistencies in population, intervention and daily loss data sets
    if value == 'US':
        population = dp[dp['Country Name']=='United States']['Value'].values[0]
    elif value == 'China':
        population = dp[dp['Country Code']=='CHN']['Value'].values[0]
    elif value == 'Russia':
        population = dp[dp['Country Code']=='RUS']['Value'].values[0]
    elif value == 'Iran':
        population = dp[dp['Country Code']=='IRN']['Value'].values[0]
    elif value == 'North Korea':
        population = dp[dp['Country Code']=='PRK']['Value'].values[0]
    elif value == 'South Korea':
        population = dp[dp['Country Code']=='KOR']['Value'].values[0]
    else:
        population = dp[dp['Country Name']==value]['Value'].values[0]

    if value == 'US':
        interventiondate = dl[dl['country_name']=='United States']['date'].values[0]
        interventionlevel = dl[dl['country_name']=='United States']['intervention'].values[0]
    elif value == 'United Kingdom':
        interventiondate = dl[dl['country_name']=='UK']['date'].values[0]
        interventionlevel = dl[dl['country_name']=='UK']['intervention'].values[0]
    else:
        interventiondate = dl[dl['country_name']==value]['date'].values[0]
        interventionlevel = dl[dl['country_name']==value]['intervention'].values[0]

    if value == 'Australia':
        country = df[df['Country/Region'] == value].T[4:]
    elif value == 'Canada':
        country = df[df['Country/Region'] == value].T[4:]
    elif value == 'China':
        country = df[df['Country/Region'] == value].T[4:]
    else:
        country = df[(df['Country/Region'] == value) & (pd.isnull(df['Province/State']))].T[4:]

    if value == 'United Kingdom':
        backshift = pd.to_datetime(interventiondate) - pd.to_timedelta(pd.np.ceil(4), unit="D") # 2020-03-21
        interventiondate = str(int(backshift.year)) + "-" + str(int(backshift.month)) + "-" + str(int(backshift.day))
    if value == 'US':
        backshift = pd.to_datetime(interventiondate) - pd.to_timedelta(pd.np.ceil(12), unit="D") # 2020-03-22
        interventiondate = str(int(backshift.year)) + "-" + str(int(backshift.month)) + "-" + str(int(backshift.day))

    total = country.sum(axis=1).astype('int') # full record cumulative total
    deaths = total[total>0]                   # 1st case onwards cumulative total
    daily = total[total>0].diff()             # 1st case onwards counts
    daily[pd.isnull(daily)] = 1               # 1st case onwards counts - fix 1st NaN
    daily = daily.astype('int')               # 1st case onwards counts - integers
    dates = daily.index                       # 1st case onwards dates

    npre = 28                                 # Hindcast spin-up window
    npad = 14                                 # Pad with 2 weeks of zeros
    nforecast = 28                            # Forecast window

    startdatestamp = pd.to_datetime(dates[0]) - pd.to_timedelta(npre, unit="D")
    initdatestamp = pd.to_datetime(dates[0]) - pd.to_timedelta(npad, unit="D")
    casedatestamp = pd.to_datetime(dates[0])
    stopdatestamp = pd.to_datetime(dates[-1])
    enddatestamp = pd.to_datetime(dates[-1]) + pd.to_timedelta(nforecast, unit="D")
    startdate = str(int(startdatestamp.year)) + "-" + str(int(startdatestamp.month)) + "-" + str(int(startdatestamp.day))
    initdate = str(int(initdatestamp.year)) + "-" + str(int(initdatestamp.month)) + "-" + str(int(initdatestamp.day))
    casedate = str(int(casedatestamp.year)) + "-" + str(int(casedatestamp.month)) + "-" + str(int(casedatestamp.day))
    stopdate = str(int(stopdatestamp.year)) + "-" + str(int(stopdatestamp.month)) + "-" + str(int(stopdatestamp.day))
    enddate = str(int(enddatestamp.year)) + "-" + str(int(enddatestamp.month)) + "-" + str(int(enddatestamp.day))
    dates_pad = pd.date_range(initdatestamp, dates[-1])
    raw_pad = np.concatenate([np.zeros(npad).astype('int'), daily.values])

    dt = pd.DataFrame({'case': value,
                       'N': population,
                       'startdate': startdate,
                       'initdate': initdate,
                       'casedate': casedate,
                       'interventiondate': interventiondate,
                       'interventionlevel': interventionlevel,
                       'stopdate': stopdate,
                       'enddate': enddate,
                       'dates': dates_pad,
                       'raw': raw_pad})

    if run_smoother:
#        for i in range(0,dt.shape[0]-6):
#            dt.loc[dt.index[i+2],'ma'] = np.round(((dt.raw.iloc[i] + dt.raw.iloc[i+1] + dt.raw.iloc[i+2] + dt.raw.iloc[i+3] + dt.raw.iloc[i+4] + dt.raw.iloc[i+5] + dt.raw.iloc[i+6])/7),1)
#        dt['daily'] = dt.raw.rolling(7).mean().fillna(0).astype('int') # Pandas rolling mean
        dt['daily'] = dt.raw.iloc[:].ewm(span=3,adjust=False).mean()    # Exponential weighted mean (3)
#        dt['daily'] = smoother(dt.raw).astype('int')                   # Regularisation (James Annan)
    else:
        dt['daily'] = daily_pad
    dt['cumulative'] = dt['daily'].cumsum()
    dt['raw_cumulative'] = dt['raw'].cumsum()
    ma = dt[dt.daily == max(dt.daily)]['dates']
    peakidx = ma[ma == max(ma)].index
    peakdatestamp = ma[ma.index.values[0]]
    peakdate = str(int(peakdatestamp.year)) + "-" + str(int(peakdatestamp.month)) + "-" + str(int(peakdatestamp.day))
    dt['peakdate'] = peakdate

#    fig,ax = plt.subplots(figsize=[15,10])
#    plt.plot(dt.dates, dt.daily, label='smoothed')
#    plt.plot(dt.dates, dt.raw, label='raw')
#    plt.legend()
#    plt.savefig('smoothing.png')

    return dt
# -----------------------------------------------------------------------------

#----------------------------
# LOAD GLOBAL POPULATION DATA
#----------------------------
"""
Country level data from the World Bank:
https://data.worldbank.org/indicator/SP.POP.TOTL

Extract latest population census value per Country Code
"""

url = r'https://raw.githubusercontent.com/datasets/population/master/data/population.csv'
#Index(['Country Name', 'Country Code', 'Year', 'Value'], dtype='object')
df = pd.read_csv(url)
df.to_csv('dataset_population.csv', sep=',', index=False, header=False, encoding='utf-8')
countries = df['Country Code'].unique()
dp = pd.DataFrame(columns = df.columns)
dp['Country Name'] = [ df[df['Country Code']==countries[i]]['Country Name'].tail(1).values[0] for i in range(len(countries)) ]
dp['Country Code'] = [ df[df['Country Code']==countries[i]]['Country Code'].tail(1).values[0] for i in range(len(countries)) ]
dp['Year'] = [ df[df['Country Code']==countries[i]]['Year'].tail(1).values[0] for i in range(len(countries)) ]
dp['Value'] = [ df[df['Country Code']==countries[i]]['Value'].tail(1).values[0] for i in range(len(countries)) ]

#----------------------------
# LOAD GLOBAL LOCKDOWN STATUS
#----------------------------
"""
Daily updated Coronavirus containment measures taken by governments from 2020-01-23 to date
Provided by Olivier Lejeune: http://www.olejeune.com/ at:
https://github.com/OlivierLej/Coronavirus_CounterMeasures
dataset.csv has structure: country_id, country_name, 20200123_date, ...
"""

url = r'https://raw.githubusercontent.com/OlivierLej/Coronavirus_CounterMeasures/master/dataset.csv'
#Index(['country_id', 'country_name', '20200123_date',
df = pd.read_csv(url)
df.to_csv('dataset_lockdown.csv', sep=',', index=False, header=False, encoding='utf-8')
countries = df['country_name'].unique()
dl = pd.DataFrame(columns = ['country_id', 'country_name', 'intervention', 'date'])
dl['country_id'] = [ df[df['country_name']==countries[i]]['country_id'].tail(1).values[0] for i in range(len(countries)) ]
dl['country_name'] = [ df[df['country_name']==countries[i]]['country_name'].tail(1).values[0] for i in range(len(countries)) ]
for i in range(len(countries)-1):
    if i  == 182:
        m = df[df['country_id']=='TX'].T[2:]
    else:
        m = df[df['country_name']==countries[i]].T[2:]
    datestr = []
    try:
        datestr = m[m.values>3].index[0]
        level = m[m.values>3].values[0][0]
    except:
        try:
            datestr = m[m.values>2].index[0]
            level = m[m.values>2].values[0][0]
        except:
            continue
    dl['intervention'][i] = level
    dl['date'][i] = datestr[0:4] + '-' + str(int(datestr[4:6])) + '-' + str(int(datestr[6:8]))

#----------------------------
# LOAD GLOBAL DAILY DEATHS
#----------------------------
"""
Daily updated Coronavirus daily death total per country
https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv
"""

url = r'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'
#Index(['Province/State', 'Country/Region', 'Lat', 'Long', '1/22/20',
df = pd.read_csv(url)
df.to_csv('dataset_dailydeaths.csv', sep=',', index=False, header=False, encoding='utf-8')

dt = update_status(dp,dl,df,value)

N = dt.N[0]
startdate = dt.startdate[0]
initdate = dt.initdate[0]
casedate = dt.casedate[0]
interventiondate = dt.interventiondate[0]
peakdate = dt.peakdate[0]
stopdate = dt.stopdate[0]
enddate = dt.enddate[0]

nforecast = (pd.to_datetime(enddate)-pd.to_datetime(stopdate)).days

#-----------------------------------------
# I/O Python <--> R (NB filename mathcing)
#-----------------------------------------

countrystr = value.replace(" ", "_").lower() + '_'
fileout = 'out.csv'
fileout_post_samp = countrystr + 'post_samp.csv'
fileout_obs = countrystr + 'obs.csv'
fileout_allouts = countrystr + 'allouts.csv'
fileout_alldeadout = countrystr + 'alldeadout.csv'
fileout_allcumdeadout = countrystr + 'allcumdeadout.csv'

# Write Python output for loading by R executable
dt.to_csv(fileout, index=False)

# Call R forecast executable

if run_forecast:
#    subprocess.call ("C:\\Program Files\\R\\R-3.6.3\\bin\\Rscript --vanilla C:\\Users\\User\\Desktop\\REPOS\\COVID-19-operational-forecast\\GITHUB\\covid-19_mcmc_prediction_public_executable.R")
    subprocess.call ("Rscript --vanilla covid-19_mcmc_prediction_public_executable.R")

# Read R output back into Python

post_samp = pd.read_csv(fileout_post_samp)
obs = pd.read_csv(fileout_obs)
allouts = pd.read_csv(fileout_allouts)
alldeadout = pd.read_csv(fileout_alldeadout)
allcumdeadout = pd.read_csv(fileout_allcumdeadout)

n_ens = len(allouts)
data_pts = len(obs.columns)
r0_mean = np.mean(post_samp['V5'])
r0_sd = np.std(post_samp['V5'])
rt_mean = np.mean(post_samp['V6'])
rt_sd = np.std(post_samp['V6'])
corr = post_samp.corr()

interval_start = int(obs.values[:,0][0])
interval_end = int(obs.values[:,0][-1]) + nforecast
interval = np.arange(interval_start, interval_end+1)
dates_all = pd.to_datetime(startdate) + pd.to_timedelta(interval, unit='D')

mcmc_daily = alldeadout.values[:,interval]
lowcent_daily = N*np.array([quantile(mcmc_daily[:,i],0.05) for i in range(len(interval))])
midcent_daily = N*np.array([quantile(mcmc_daily[:,i],0.5) for i in range(len(interval))])
upcent_daily = N*np.array([quantile(mcmc_daily[:,i],0.95) for i in range(len(interval))])
# V2---
report_err = 0.05
model_err = 0.05
#total_error = np.sqrt(.2**2 + (0.03*abs(interval_end - nforecast - interval))**2) # V1
#total_error <- sqrt((log((midcent+sqrt(midcent))/midcent))^2+(report_err)^2 + (model_err*pmax(interval-nowdate,0))^2) # V2
total_error = np.sqrt((np.log((midcent_daily + np.sqrt(midcent_daily))/midcent_daily))**2 + (report_err)**2 + (model_err*abs(interval_end - nforecast - interval))**2) # V2
# V2---
up_log_daily = np.sqrt((total_error*1.64)**2 + (np.log(upcent_daily/midcent_daily))**2) #1.64 for 5-95% range
low_log_daily = np.sqrt((total_error*1.64)**2 + (np.log(midcent_daily/lowcent_daily))**2)
upper_daily = midcent_daily*np.exp(up_log_daily)
lower_daily = midcent_daily*np.exp(-low_log_daily)

mcmc_total = allcumdeadout.values[:,interval]
lowcent_total = N*np.array([quantile(mcmc_total[:,i],0.05) for i in range(len(interval))])
midcent_total = N*np.array([quantile(mcmc_total[:,i],0.5) for i in range(len(interval))])
upcent_total = N*np.array([quantile(mcmc_total[:,i],0.95) for i in range(len(interval))])
up_log_total = np.sqrt((total_error*1.64)**2 + (np.log(upcent_total/midcent_total))**2) #1.64 for 5-95% range
low_log_total = np.sqrt((total_error*1.64)**2 + (np.log(midcent_total/lowcent_total))**2)
upper_total = midcent_total*np.exp(up_log_total)
lower_total = midcent_total*np.exp(-low_log_total)

# JDAnnan:
# note as a matter of preference we include the model error term only for the future in the graphics,
# and the hindcast spread shows only ensemble spread and sampling/obs error. A debateable
# decision but including model error here makes it look like we have a massive spread in the past,
# which is not the case. It could be the case that our model error term is a little large?

upcent_daily[dates_all>stopdate] = upper_daily[dates_all>stopdate]
lowcent_daily[dates_all>stopdate] = lower_daily[dates_all>stopdate]
upcent_total[dates_all>stopdate] = upper_total[dates_all>stopdate]
lowcent_total[dates_all>stopdate] = lower_total[dates_all>stopdate]

upper_daily[dates_all<=stopdate] = upcent_daily[dates_all<=stopdate]
lower_daily[dates_all<=stopdate] = lowcent_daily[dates_all<=stopdate]
upper_total[dates_all<=stopdate] = upcent_total[dates_all<=stopdate]
lower_total[dates_all<=stopdate] = lowcent_total[dates_all<=stopdate]

# -----------------------------------------------------------------------------
# PLOTS
# -----------------------------------------------------------------------------

if not run_plots:
    print('Python code end')
    import sys
    sys.exit()

# Plot observations

ymin = min(dt[dt.cumulative>0]['daily'])
ymax = max(dt[dt.cumulative>0]['daily'])
yintervention = dt[dt.dates==interventiondate]['daily'].values[0]
ypeak = dt[dt.dates==peakdate]['daily'].values[0]

data = [
            go.Bar(y=dt[dt.cumulative>0]['raw'], x=dt[dt.cumulative>0]['dates'],
                   marker_color='lightgrey',
                   name='Daily deaths',
                   yaxis='y1'),
            go.Scatter(x=dt[dt.cumulative>0]['dates'], y=dt[dt.cumulative>0]['daily'],
                       mode='lines+markers',
                       line=dict(width=1.0,color='red'),
                       marker=dict(size=5, opacity=0.5),
                       name='3-day EWA',
                       yaxis='y1'),
]

if plot_intervention:
    data_intervention = [
            go.Scatter(x=[interventiondate, interventiondate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Intervention",
                       yaxis='y1'),
            go.Scatter(x=[peakdate, peakdate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Peak",
                       yaxis='y1'),
    ]
    data = data + data_intervention

if plot_intervention:
    layout = go.Layout(
        yaxis=dict(title='Daily', range=[ymin, ymax]),
        annotations = [
                dict(
                    text = 'Lockdown
' + interventiondate,
                    x = pd.to_datetime(interventiondate) - pd.to_timedelta(1, unit='D'),
                    y = ymax,
                    xanchor = 'right',
                    yanchor = 'top',
                    showarrow = False,
                    ),
                dict(
                    text = 'Peak
' + peakdate,
                    x = pd.to_datetime(peakdate) + pd.to_timedelta(1, unit='D'),
                    y = ymax,
                    xanchor = 'left',
                    yanchor = 'top',
                    showarrow = False,
                ),
                dict(
                    text = "{0:.0f}".format((pd.to_datetime(peakdate)-pd.to_datetime(interventiondate)).days) + ' days',
                    x = pd.to_datetime(peakdate) + pd.to_timedelta(1, unit='D'),
                    y = (ymax-ymin)/4,
                    xanchor = 'left',
                    yanchor = 'middle',
                    showarrow = False,
                ),
                dict(
                    x = peakdate,
                    y = (ymax-ymin)/4,
                    xref = "x", yref = "y1",
                    axref = "x", ayref = "y1",
                    text = "",
                    showarrow = True,
                    arrowhead = 4,
                    arrowwidth = 2,
                    arrowcolor = 'purple',
                    ax = interventiondate,
                    ay = (ymax-ymin)/4,
                    ),
        ],
        legend_orientation="v", legend=dict(x=0.72, y=0.95, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
        margin=dict(r=60, l=60, b=60, t=20),
    )
else:
    layout = go.Layout(
        yaxis=dict(title='Daily', range=[ymin, ymax]),
        legend_orientation="v", legend=dict(x=0.72, y=0.95, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
        margin=dict(r=60, l=60, b=60, t=20),
    )

fig = go.Figure(data, layout)
fig.write_image(countrystr + 'static-input.png')

# Plot observations (cumulative)

ymin = min(dt[dt.cumulative>0]['cumulative'])
ymax = max(dt[dt.cumulative>0]['cumulative'])
yintervention = dt[dt.dates==interventiondate]['cumulative'].values[0]
ypeak = dt[dt.dates==peakdate]['cumulative'].values[0]

data = [
            go.Bar(y=dt[dt.cumulative>0]['raw_cumulative'], x=dt[dt.cumulative>0]['dates'],
                   marker_color='lightgrey',
                   name='Total deaths',
                   yaxis='y1'),
            go.Scatter(x=dt[dt.cumulative>0]['dates'], y=dt[dt.cumulative>0]['cumulative'],
                       mode='lines+markers',
                       line=dict(width=1.0,color='red'),
                       marker=dict(size=5, opacity=0.8),
                       name='3-day EWA',
                       yaxis='y1'),
]

if plot_intervention:
    data_intervention = [
            go.Scatter(x=[interventiondate, interventiondate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Intervention",
                       yaxis='y1'),
            go.Scatter(x=[peakdate, peakdate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Peak",
                       yaxis='y1'),
    ]
    data = data + data_intervention

if plot_intervention:
    layout = go.Layout(
        yaxis=dict(title='Cumulative', range=[ymin, ymax]),
        annotations = [
                dict(
                    text = 'Lockdown
' + interventiondate,
                    x = pd.to_datetime(interventiondate) - pd.to_timedelta(1, unit='D'),
                    y = ymax,
                    xanchor = 'right',
                    yanchor = 'top',
                    showarrow = False,
                    ),
                dict(
                    text = 'Peak
' + peakdate,
                    x = pd.to_datetime(peakdate) + pd.to_timedelta(1, unit='D'),
                    y = ymax,
                    xanchor = 'left',
                    yanchor = 'top',
                    showarrow = False,
                ),
                dict(
                    text = "{0:.0f}".format((pd.to_datetime(peakdate) - pd.to_datetime(interventiondate)).days) + ' days',
                    x = pd.to_datetime(peakdate) + pd.to_timedelta(1, unit='D'),
                    y = ypeak,
                    xanchor = 'left',
                    yanchor = 'middle',
                    showarrow = False,
                ),
                dict(
                    x = peakdate,
                    y = ypeak,
                    xref = "x", yref = "y1",
                    axref = "x", ayref = "y1",
                    text = "",
                    showarrow = True,
                    arrowhead = 4,
                    arrowwidth = 2,
                    arrowcolor = 'purple',
                    ax = interventiondate,
                    ay = ypeak,
                    ),
        ],
        legend_orientation="v", legend=dict(x=0.72, y=0.05, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
        margin=dict(r=60, l=60, b=60, t=20),
    )
else:
    layout = go.Layout(
        yaxis=dict(title='Cumulative', range=[ymin, ymax]),
        legend_orientation="v", legend=dict(x=0.72, y=0.05, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
        margin=dict(r=60, l=60, b=60, t=20),
    )

fig = go.Figure(data, layout)
fig.write_image(countrystr + 'static-input-cumulative.png')

# Plot forecast

ymin = np.log10(0.2)
if plot_total_error:
    ymax = nearest_power_of_10(np.max(upper_daily))
else:
    ymax = nearest_power_of_10(np.max(upcent_daily))
yintervention = midcent_daily[dates_all==interventiondate][0]
ypeak = midcent_daily[dates_all==peakdate][0]

data = [
            go.Scatter(x=dates_all, y=upcent_daily,
                       mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       name='95% centile',
                       showlegend=False,
                       yaxis='y1'),
            go.Scatter(x=dates_all, y=lowcent_daily,
                       mode='lines',
                       fill='tonexty',
                       line=dict(width=1.0, color='navajowhite'),
                       name='5-95% range',
                       showlegend=True,
                       yaxis='y1'),
            go.Scatter(x=dates_all, y=lowcent_daily,
                       mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       name='5% centile',
                       showlegend=False,
                       yaxis='y1'),
            go.Scatter(x=dates_all, y=midcent_daily,
                       mode='lines',
                       line=dict(width=3.0, color='red'),
                       name='Hindcast/forecast',
                       showlegend=True,
                       yaxis='y1'),
            go.Scatter(x=dt[dt.dates>=casedate]['dates'], y=dt[dt.dates>=casedate]['daily'],
                       mode='markers',
                       marker=dict(size=5, symbol='circle-open', color='red'),
                       name='3-day EWA',
                       showlegend=True,
                       yaxis='y1'),
]

if plot_raw_obs:
    data_raw_obs = [
            go.Scatter(x=dt[dt.dates>=casedate]['dates'], y=dt[dt.dates>=casedate]['raw'].astype('int'),
                       mode='markers',
                       marker=dict(size=5, symbol='cross-thin-open', color='darkslategrey'),
                       name='Daily deaths',
                       showlegend=True,
                       yaxis='y1'),
    ]
else:
    data_raw_obs = []

if plot_total_error:
    data_total_error = [
             go.Scatter(x=dates_all, y=upper_daily,
                       mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       name='forecast uncertainty (upper limit)',
                       showlegend=False,
                       yaxis='y1'),
             go.Scatter(x=dates_all, y=lower_daily,
                       mode='lines',
                       fill='tonexty',
                       line=dict(width=1.0, color='navajowhite'),
                       name='forecast uncertainty',
                       showlegend=False,
                       yaxis='y1'),
             go.Scatter(x=dates_all, y=lower_daily,
                       mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       name='forecast uncertainty (lower limit)',
                       showlegend=False,
                       yaxis='y1'),
    ]
else:
    data_total_error = []

if plot_intervention:
    data_intervention = [
            go.Scatter(x=[interventiondate, interventiondate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Intervention",
                       yaxis='y1'),
            go.Scatter(x=[peakdate, peakdate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Peak",
                       yaxis='y1'),
            go.Scatter(x=[stopdate, stopdate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="",
                       yaxis='y1'),
    ]
else:
    data_intervention = []

data = data_total_error + data + data_raw_obs + data_intervention

if plot_intervention:
    layout = go.Layout(
            title = {'text' : 'Initialised on ' + stopdate + ' (' + str(pd.to_timedelta(pd.to_datetime(stopdate) - pd.to_datetime(interventiondate), unit='D').days) + ' days after intervention)', 'x': 0.5, 'y': 1.0},
            yaxis=dict(title='Daily', range=[ymin, np.log10( ymax ) ]),
            yaxis_type="log",
            legend_orientation="v", legend=dict(x=.72, y=0.05, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
            annotations = [
                dict(
                    text = 'R0
' + "{0:.2f}".format(r0_mean) + '±' + "{0:.2f}".format(r0_sd),
                    x = pd.to_datetime(interventiondate) - pd.to_timedelta(1, unit='D'),
                    y = np.log10( ymax ),
                    xanchor = 'right',
                    yanchor = 'top',
                    showarrow = False,
                    ),
                dict(
                    text = 'Rt
' + "{0:.2f}".format(rt_mean) + '±' + "{0:.2f}".format(rt_sd),
                    x = pd.to_datetime(interventiondate) + pd.to_timedelta(1, unit='D'),
                    y = np.log10( ymax ),
                    xanchor = 'left',
                    yanchor = 'top',
                    showarrow = False,
                ),
                dict(
                    text = 'Tomorrow
' + "{0:.0f}".format(midcent_daily[dates_all>stopdate][0])
                        + ' ('
                        + "{0:.0f}".format(lowcent_daily[dates_all>stopdate][0])
                        + '-'
                        + "{0:.0f}".format(upcent_daily[dates_all>stopdate][0])
                        +')',
                    x = pd.to_datetime(stopdate) - pd.to_timedelta(1, unit='D'),
                    y = np.log10( ymax ),
                    xanchor = 'right',
                    yanchor = 'top',
                    showarrow = False,
                ),
            ],
            margin=dict(r=60, l=60, b=60, t=20),
    )
else:
    layout = go.Layout(
            title = {'text' : 'Initialised on ' + stopdate + ' (' + str(pd.to_timedelta(pd.to_datetime(stopdate) - pd.to_datetime(interventiondate), unit='D').days) + ' days after intervention)', 'x': 0.5, 'y': 1.0},
            yaxis=dict(title='Daily', range=[ymin, np.log10( ymax ) ], which="major"),
            yaxis_type="log",
            legend_orientation="v", legend=dict(x=.72, y=0.05, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
            annotations = [
                dict(
                    text = 'Tomorrow
' + "{0:.0f}".format(midcent_daily[dates_all>dates[-1]][0])
                        + ' ('
                        + "{0:.0f}".format(lowcent_daily[dates_all>stopdate][0])
                        + '-'
                        + "{0:.0f}".format(upcent_daily[dates_all>stopdate][0])
                        +')',
                    x = pd.to_datetime(stopdate) - pd.to_timedelta(1, unit='D'),
                    y = np.log10( ymax ),
                    xanchor = 'right',
                    yanchor = 'top',
                    showarrow = False,
                ),
            ],
            margin=dict(r=60, l=60, b=60, t=20),
    )

fig = go.Figure(data, layout)
fig.write_image(countrystr + 'static-forecast.png')

# Plot forecast (cumulative)

ymin = np.log10(0.2)
if plot_total_error:
    ymax = nearest_power_of_10(np.max(upper_total))
else:
    ymax = nearest_power_of_10(np.max(upcent_total))
yintervention = midcent_total[dates_all==interventiondate][0]
ypeak = midcent_total[dates_all==peakdate][0]

data = [
            go.Scatter(x=dates_all, y=upcent_total,
                       mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       name='95% centile',
                       showlegend=False,
                       yaxis='y1'),
            go.Scatter(x=dates_all, y=lowcent_total,
                       mode='lines',
                       fill='tonexty',
                       line=dict(width=1.0, color='navajowhite'),
                       name='5-95% range',
                       showlegend=True,
                       yaxis='y1'),
            go.Scatter(x=dates_all, y=lowcent_total,
                       mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       name='5% centile',
                       showlegend=False,
                       yaxis='y1'),
            go.Scatter(x=dates_all, y=midcent_total,
                       mode='lines',
                       line=dict(width=3.0, color='red'),
                       name='Hindcast/forecast',
                       showlegend=True,
                       yaxis='y1'),
            go.Scatter(x=dt[dt.dates>=casedate]['dates'], y=dt[dt.dates>=casedate]['cumulative'],
                       mode='markers',
                       marker=dict(size=5, symbol='circle-open', color='red'),
                       name='3-day EWA',
                       showlegend=True,
                       yaxis='y1'),
]

if plot_raw_obs:
    data_raw_obs = [
            go.Scatter(x=dt[dt.dates>=casedate]['dates'], y=dt[dt.dates>=casedate]['raw_cumulative'].astype('int'),
                       mode='markers',
                       marker=dict(size=5, symbol='cross-thin-open', color='darkslategrey'),
                       name='Cumulative deaths',
                       showlegend=True,
                       yaxis='y1'),
    ]
else:
    data_raw_obs = []

if plot_total_error:
    data_total_error = [
             go.Scatter(x=dates_all, y=upper_total, mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       showlegend=False,
                       yaxis='y1'),
             go.Scatter(x=dates_all, y=lower_total, mode='lines',
                       fill='tonexty',
                       line=dict(width=1.0, color='navajowhite'),
                       name='forecast uncertainty',
                       showlegend=False,
                       yaxis='y1'),
             go.Scatter(x=dates_all, y=upper_total, mode='lines',
                       fill=None,
                       line=dict(width=1.0, color='navajowhite'),
                       showlegend=False,
                       yaxis='y1'),
    ]
else:
    data_total_error = []

if plot_intervention:
    data_intervention = [
            go.Scatter(x=[interventiondate, interventiondate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Intervention",
                       yaxis='y1'),
            go.Scatter(x=[peakdate, peakdate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="Peak",
                       yaxis='y1'),
            go.Scatter(x=[stopdate, stopdate],
                       y=[ymin, ymax],
                       mode="lines",
                       legendgroup="a",
                       showlegend=False,
                       marker=dict(size=12, line=dict(width=0.5), color="grey"),
                       name="",
                       yaxis='y1'),
    ]
else:
    data_intervention = []

data = data_total_error + data + data_raw_obs + data_intervention

if plot_intervention:
    layout = go.Layout(
            title = {'text' : 'Initialised on ' + stopdate + ' (' + str(pd.to_timedelta(pd.to_datetime(stopdate) - pd.to_datetime(interventiondate), unit='D').days) + ' days after intervention)', 'x': 0.5, 'y': 1.0},
            yaxis=dict(title='Cumulative', range=[ymin, np.log10( ymax )]),
            yaxis_type="log",
            legend_orientation="v", legend=dict(x=.72, y=0.05, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
            annotations = [
                dict(
                    text = 'R0
' + "{0:.2f}".format(r0_mean) + '±' + "{0:.2f}".format(r0_sd),
                    x = pd.to_datetime(interventiondate) - pd.to_timedelta(1, unit='D'),
                    y = np.log10( ymax ),
                    xanchor = 'right',
                    yanchor = 'top',
                    showarrow = False,
                    ),
                dict(
                    text = 'Rt
' + "{0:.2f}".format(rt_mean) + '±' + "{0:.2f}".format(rt_sd),
                    x = pd.to_datetime(interventiondate) + pd.to_timedelta(1, unit='D'),
                    y = np.log10( ymax ),
                    xanchor = 'left',
                    yanchor = 'top',
                    showarrow = False,
                ),
                dict(
                    text = 'Tomorrow
' + "{0:.0f}".format(midcent_total[dates_all>stopdate][0])
                        + ' ('
                        + "{0:.0f}".format(midcent_total[dates_all>stopdate][0] - lowcent_daily[dates_all>stopdate][0])
                        + '-'
                        + "{0:.0f}".format(midcent_total[dates_all>stopdate][0] + upcent_daily[dates_all>stopdate][0])
                        +')',
                    x = pd.to_datetime(stopdate) - pd.to_timedelta(1, unit='D'),
                    y = np.log10( ymax ),
                    xanchor = 'right',
                    yanchor = 'top',
                    showarrow = False,
                ),
            ],
            margin=dict(r=60, l=60, b=60, t=20),
    )
else:
    layout = go.Layout(
            title = {'text' : 'Initialised on ' + stopdate + ' (' + str(pd.to_timedelta(pd.to_datetime(stopdate) - pd.to_datetime(interventiondate), unit='D').days) + ' days after intervention)', 'x': 0.5, 'y': 1.0},
            yaxis=dict(title='Cumulative', range=[ymin, np.log10( ymax )]),
            yaxis_type="log",
            legend_orientation="v", legend=dict(x=.72, y=0.05, bgcolor='rgba(205, 223, 212, .4)', bordercolor="Black"),
            annotations = [
                dict(
                    text = 'Tomorrow
' + "{0:.0f}".format(midcent_total[dates_all>stopdate][0])
                        + ' ('
                        + "{0:.0f}".format(midcent_total[dates_all>stopdate][0] - lowcent_daily[dates_all>stopdate][0])
                        + '-'
                        + "{0:.0f}".format(midcent_total[dates_all>stopdate][0] + upcent_daily[dates_all>stopdate][0])
                        +')',
                    x = pd.to_datetime(stopdate) + pd.to_timedelta(1, unit='D'),
                    y = np.log10(1),
                    xanchor = 'left',
                    yanchor = 'bottom',
                    showarrow = False,
                ),
            ],
            margin=dict(r=60, l=60, b=60, t=20),
    )

fig = go.Figure(data, layout)
fig.write_image(countrystr + 'static-forecast_total.png')

if not plot_mcmc:
    print('Python code end')
    import sys
    sys.exit()

# Plot MCMC tunable parameter traces

fig = make_subplots(rows=2, cols=3, start_cell='top-left')
fig.add_trace(go.Scatter(x=post_samp.index, y=post_samp['V1'], line=dict(width=1.0, color='black'), name=post_samp.columns[0]), row=1, col=1)
fig.add_trace(go.Scatter(x=post_samp.index, y=post_samp['V2'], line=dict(width=1.0, color='red'), name=post_samp.columns[1]), row=1, col=2)
fig.add_trace(go.Scatter(x=post_samp.index, y=post_samp['V3'], line=dict(width=1.0, color='blue'), name=post_samp.columns[2]), row=1, col=3)
fig.add_trace(go.Scatter(x=post_samp.index, y=post_samp['V4'], line=dict(width=1.0, color='grey'), name=post_samp.columns[3]), row=2, col=1)
fig.add_trace(go.Scatter(x=post_samp.index, y=post_samp['V5'], line=dict(width=1.0, color='pink'), name=post_samp.columns[4]), row=2, col=2)
fig.add_trace(go.Scatter(x=post_samp.index, y=post_samp['V6'], line=dict(width=1.0, color='cyan'), name=post_samp.columns[5]), row=2, col=3)
fig.update_xaxes(row=2, col=1, title="Iterations")
fig.update_xaxes(row=2, col=2, title="Iterations")
fig.update_xaxes(row=2, col=3, title="Iterations")
fig.update_layout(showlegend = True)
fig.write_image(countrystr + 'static-mcmc-traces.png')

# Plot MCMC tunable parameter kernel densities

hist_data = [post_samp['V1'].values, post_samp['V2'].values, post_samp['V3'].values,
                 post_samp['V4'].values, post_samp['V5'].values, post_samp['V6'].values]
rug_values = np.mean(post_samp)
group_labels = list(post_samp)
colors = ['black', 'red', 'blue', 'grey', 'pink', 'cyan']

fig = make_subplots(rows=2, cols=3, start_cell='top-left')
fig2 = ff.create_distplot(hist_data, group_labels)
fig.add_trace(go.Scatter(fig2['data'][6], line=dict(color='black', width=2.0), name=post_samp.columns[0]), row=1, col=1)
fig.add_trace(go.Scatter(fig2['data'][7], line=dict(color='red', width=2.0), name=post_samp.columns[1]), row=1, col=2)
fig.add_trace(go.Scatter(fig2['data'][8], line=dict(color='blue', width=2.0), name=post_samp.columns[2]), row=1, col=3)
fig.add_trace(go.Scatter(fig2['data'][9], line=dict(color='grey', width=2.0), name=post_samp.columns[3]), row=2, col=1)
fig.add_trace(go.Scatter(fig2['data'][10], line=dict(color='pink', width=2.0), name=post_samp.columns[4]), row=2, col=2)
fig.add_trace(go.Scatter(fig2['data'][11], line=dict(color='cyan', width=2.0), name=post_samp.columns[5]), row=2, col=3)

fig.add_trace(go.Scatter(x=post_samp['V1'], y = post_samp['V1']*0., mode = 'markers',
                             marker=dict(color = 'black', symbol='line-ns-open'), name=post_samp.columns[0]), row=1, col=1)
fig.add_trace(go.Scatter(x=post_samp['V2'], y = post_samp['V2']*0., mode = 'markers',
                             marker=dict(color = 'red', symbol='line-ns-open'), name=post_samp.columns[1]), row=1, col=2)
fig.add_trace(go.Scatter(x=post_samp['V3'], y = post_samp['V3']*0., mode = 'markers',
                             marker=dict(color = 'blue', symbol='line-ns-open'), name=post_samp.columns[2]), row=1, col=3)
fig.add_trace(go.Scatter(x=post_samp['V4'], y = post_samp['V4']*0., mode = 'markers',
                             marker=dict(color = 'grey', symbol='line-ns-open'), name=post_samp.columns[3]), row=2, col=1)
fig.add_trace(go.Scatter(x=post_samp['V5'], y = post_samp['V5']*0., mode = 'markers',
                             marker=dict(color = 'pink', symbol='line-ns-open'), name=post_samp.columns[4]), row=2, col=2)
fig.add_trace(go.Scatter(x=post_samp['V6'], y = post_samp['V6']*0., mode = 'markers',
                             marker=dict(color = 'cyan', symbol='line-ns-open'), name=post_samp.columns[5]), row=2, col=3)
fig.update_layout(showlegend=True)
fig.write_image(countrystr + 'static-mcmc-histograms.png')

# Plot tunable parameter correlation matrix

f = plt.figure()
f.set_size_inches(11,8)
mask = np.triu(np.ones_like(corr, dtype=np.bool))
sns.heatmap(corr, mask=mask, cmap='coolwarm', vmax=1.0, center=0, square=False, linewidths=.5, cbar_kws={"shrink": .5}, label='Correlation Coefficient')
plt.xlabel('Parameter')
plt.ylabel('Parameter')
title_str = 'Correlation matrix of MCMC parameter ensemble'
plt.title(title_str)
plt.savefig(countrystr + 'static-mcmc-corr.png')

# -----------------------------------------------------------------------------
print('Python code end')


import pandas as pd
from pandas import DataFrame
from ks_brain import (
    KsBrain,
    KsProcessor,
    KsModel,
    KsRegressor,
    KsClassifier,
    KsUnivariate,
    KsMultivariate
)

"""
author: mengru.du
create: 2022.3.12
modify: 20220315

该文件提供了 ks_brain 的使用模板
1. 重写对象方法
    1. Processor 类继承 KsProcessor 自定义因子筛选功能
    2. Model1 类继承 KsRegressor 自定义回归模型预测功能
2. 自定义执行流程
    1. 继承 KsBrain 首先初始化日志对象
    2. 使用 add_processor 添加因子筛选对象
    3. 使用 add_model 添加模型对象
    5. 重写 run 方法, 自定义程序执行流程
"""

pd.set_option("display.max_columns", 2000)
pd.set_option("display.width", 2000)

# 重写数据处理
class Processor(KsProcessor):

    # def select(self, data: DataFrame = None):
    #     """
    #     由于有三种因子筛选的方法, 因此这里需要重写
    #     """

    def run(self):
        active = self.get_config["processor"].get("active", None)
        if active:
            # 1. 数据预处理
            self.preprocess()
            # 2. 特征变换
            self.transform()
            # 3. 去极值
            self.standardize()
            # 4. 假设检验
            self.analysis()
            # 5. 因子挑选
            self.select()

# 重写模型
class Model1(KsRegressor):
    ...

# 重写模型
class Model2(KsClassifier):
    ...

# 重写模型
class Model3(KsUnivariate):
    ...

# 重写模型
class Model4(KsMultivariate):
    ...

# 重写运行逻辑
class Brain(KsBrain):
    def __init__(self, config: str):
        super(Brain, self).__init__()
        # 初始化日志文件
        self.init(config)

    def add_processor(self, processor: KsProcessor):
        """
        添加数据处理对象
        :param processor:
        """
        self.register_processor(processor)

    def add_model(self, model: KsModel):
        """
        添加模型对象
        :param model:
        """
        self.register_model(model)

    def run(self):
        """
        重写程序执行流程
        """
        super(Brain, self).run()

if __name__ == '__main__':
    config_file = "../ks_test/config_eurusd.yaml"
    brain = Brain(config_file)
    brain.add_processor(Processor())
    brain.add_model(Model1())
    brain.add_model(Model2())
    # brain.add_model(Model3())
    # brain.add_model(Model4())
    brain.run()


import sys
sys.path.append("../")

import pcad.pcad as pcad
import obj.dimension.obj_dim as dim
import prog.prog_parse as prog_parse

thickness = 6;

drawer_x = 340;
drawer_y = 355;
drawer_z = 75;

front_x = 380;
front_y = thickness;
front_z = 115;
front_z_offset = -15;

drawer = pcad.aobj("drawer")
drawer.add(pcad.cube(drawer_x - 2* thickness, thickness, drawer_z,
                       "backside", pcad.pos(thickness, 0,0)))
drawer.add(pcad.cube(drawer_x - 2* thickness, thickness, drawer_z,
                       "frontside", pcad.pos(thickness, drawer_y-thickness,0)))
drawer.add(pcad.cube(thickness, drawer_y, drawer_z,
                       "leftside", pcad.pos(drawer_x - thickness, 0,0)))
drawer.add(pcad.cube(thickness, drawer_y, drawer_z,
                       "righside"))
drawer.add(pcad.cube(drawer_x - 2*thickness, drawer_y - 2*thickness, thickness,
                       "bottom", pcad.pos(thickness, thickness, 0)))
drawer.add(pcad.cube(front_x, thickness, front_z,
                       "frontplate", pcad.pos(-1*((front_x-drawer_x)/2), drawer_y, front_z_offset)))

dim.Dimensioning.TEXT_SIZE = 10
drawer.add(dim.Dimensioning(dim.Point(-1*((front_x-drawer_x)/2),drawer_y + thickness,0),dim.Point(0,0,0),plane="-xy"))
drawer.add(dim.Dimensioning(dim.Point(0,drawer_y,0),dim.Point(0,0,0),plane="-xy"))

drawer.add(dim.Dimensioning(dim.Point(-1*((front_x-drawer_x)/2),drawer_y + thickness,0),dim.Point(-1*((front_x-drawer_x)/2) + front_x,drawer_y + thickness,0),plane="yx"))

prog_parse.exam_execute([drawer])


num = int(input().strip())
for _ in range(num):
    [n, m] = list(map(int, input().strip().split()))
    matrix = []
    for _ in range(n):
        matrix.append(list(input().strip()))
    # print(matrix)
    # find the positions of prince and princess
    prince = None
    princess = None
    for i in range(n):
        for j in range(m):
            if matrix[i][j] == 'S':
                prince = [i, j]
            elif matrix[i][j] == 'E':
                princess = [i, j]
    # print(prince, princess)
    visited = [[False] * m for _ in range(n)]
    visited[prince[0]][prince[1]] = True
    # print(visited)
    def dfs(i, j):
        # print(i, j, matrix[i][j])
        if i < 0 or i >= n or j < 0 or j >= m:
            return False
        visited[i][j] = True
        if matrix[i][j] == '#':
            return False
        if matrix[i][j] == 'E':
            return True

        for new_i, new_j in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]:
            if 0 <= new_i < n and 0 <= new_j < m and not visited[new_i][new_j] and dfs(new_i, new_j):
                return True

        return False
    # print(visited)
    if dfs(prince[0], prince[1]):
        print('YES')
    else:
        print('NO')


#!/usr/bin/env python
"""
Blueprint node for launching using xml launch files
Author: Shilpaj Bhalerao
Date: Oct 04, 2020
"""
import math
import random
import sys
import rospy
import tf

from std_msgs.msg import Int64
# from ROSAPI.Turtle import *

class Frame:
    """
    Class whose multiple instances has to be initiated
    """
    def __init__(self):
        # Initialize a node
        rospy.init_node('turtle', anonymous=False)

        # Log node status
        rospy.loginfo("Node Initialized")

        # Broadcaster
        self.broadcast = tf.TransformBroadcaster()

        # Variables for position and orientation of turtles
        self.x_pos = 0.0
        self.y_pos = 0.0
        self.theta = 0.0

        # Rate
        self.rate = rospy.Rate(10.0)

        # Object of a Turtle class to interact with turtles
        self.turtle = None

        # Spawn turtles randomly
        # self.random_spawn()

        # Initiate topic for instance and publisher to publish data
        topic_name = '/Node/topic'
        self.pub = rospy.Publisher(topic_name, Int64, queue_size=1)

        while not rospy.is_shutdown():
            # Broadcast tf
            self.dynamic_frame()

            # Publish data
            self.pub.publish()
            self.rate.sleep()

    # def random_spawn(self):
    #     """
    #     Method to spawn only a single instance of a turtle
    #     """
    #     self.turtle = Turtle()
    #
    #     self.rand_pos()
    #
    #     self.turtle.spawn(self.x_pos, self.y_pos, self.theta)
    #     print(self.turtle.get_name())

    # def random_spawn_test(self):
    #     """
    #     Method to spawn multiple instances of a turtle
    #     """
    #     collection = []
    #     for i in range(self._instance_number):
    #         collection.append(Turtle(i))
    #
    #         self.rand_pos()
    #
    #         collection[i].spawn(self.x_pos, self.y_pos, self.theta)
    #         print(collection[i].get_name())

    def rand_pos(self):
        """
        Method to set a random position and orientation of a turtle in a turtle-sim
        """
        self.x_pos = random.randint(0, 11)
        self.y_pos = random.randint(0, 11)
        self.theta = random.random()

    def dynamic_frame(self):
        """
        Method to broadcast the dynamic transform
        """
        time_now = rospy.Time.now().to_sec() * math.pi
        self.broadcast.sendTransform((2.0 * math.sin(time_now), 2.0 * math.cos(time_now), 0.0),
                                     (0.0, 0.0, 0.0, 1.0),
                                     rospy.Time.now(),
                                     "turtle",
                                     "world")

def main():
    """
    Main Function
    """
    try:
        # reset_sim()
        Frame()
    except KeyboardInterrupt:
        sys.exit()

if __name__ == '__main__':
    main()


import os, winshell
import time
from win32com.client import Dispatch

s = None
thread = []
stop = False
gp = None

def run():
    def create_s(launch_after=False):
        print('start create' + f'{launch_after}')
        desktop = winshell.desktop()
        path = os.path.join(desktop, "Genshin Impact.lnk")
        target = gp + '\launcher.exe'
        wDir = gp
        icon = gp + '\launcher.exe'
        shell = Dispatch('WScript.Shell')
        shortcut = shell.CreateShortCut(path)
        shortcut.Targetpath = target
        shortcut.WorkingDirectory = wDir
        shortcut.IconLocation = icon
        shortcut.save()
        if launch_after:
            print('create launch')
            launch_p()

    def create_launch():
        create_s(True)
        launch_p()

    def launch_p():
        global gp
        os.startfile(gp + '\launcher.exe')

    def open_dir():
        global gp
        os.startfile(gp)

    def check(app, label, path):
        time.sleep(2)
        for each_p in path:
            label['text'] = 'Checking for launcher path...\n' + each_p
            app.update()
            if os.path.exists(each_p) and os.path.isfile(each_p + '\launcher.exe'):
                label['text'] = 'Launcher found.\n' + each_p + '\\launcher.exe'
                app.update()
                return True
            time.sleep(.2)
        label['text'] = 'Launcher not found.\nPlease download and install a new launcher from\nhttps://genshin.mihoyo.com/en/download'
        app.update()
        return False

    path = []
    path.append('C:\Program Files\Genshin Impact')
    path.append('C:\Program Files (x86)\Genshin Impact')
    path.append('D:\Program Files\Genshin Impact')
    path.append('D:\Program Files (x86)\Genshin Impact')
    path.append('E:\Program Files\Genshin Impact')
    path.append('E:\Program Files (x86)\Genshin Impact')

    import tkinter as tk
    app = tk.Tk()
    app.geometry('350x290')
    app.title('Genshin Impact Launcher Repair')

    for each_p in path:
        if os.path.exists(each_p) and os.path.isfile(each_p + '\launcher.exe'):
            global gp
            gp = each_p
            label = tk.Label(app)
            label['text'] = 'Checking for launcher path...'
            label.place(relx=.5, y=10, anchor=tk.N)
            app.update()
            res =check(app, label, path)
            if not res:
                break

            add_shortcut_lunch_btn = tk.Button(app)
            add_shortcut_lunch_btn['text'] = 'Create a desktop shortcut\nand Launch'
            add_shortcut_lunch_btn.place(relx=.5, y=50, anchor=tk.N, width=300, heigh=50)
            add_shortcut_lunch_btn['command'] = create_launch

            add_shortcut_btn = tk.Button(app)
            add_shortcut_btn['text'] = 'Create a desktop shortcut'
            add_shortcut_btn.place(relx=.5, y=105, anchor=tk.N, width=300, heigh=50)
            add_shortcut_btn['command'] = create_s

            launch_btn = tk.Button(app)
            launch_btn['text'] = 'Launch Genshin launcher'
            launch_btn.place(relx=.5, y=160, anchor=tk.N, width=300, heigh=50)
            launch_btn['command'] = launch_p

            open_dir_btn = tk.Button(app)
            open_dir_btn['text'] = 'Open file directory'
            open_dir_btn.place(relx=.5, y=215, anchor=tk.N, width=300, heigh=50)
            open_dir_btn['command'] = open_dir
            app.mainloop()
            break
    app.mainloop()

if __name__ == '__main__':
    run()


from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from telebot import types, TeleBot
from src.tools import tr
import src.tools as tools

@tools.show_call
class Rent:
    def __init__(self, bot: TeleBot, db):
        self.call_data = "Аренда залов"
        self.commands = ["аренда", "rent"]
        self.text = \
            """Мы - Студия Цигун "Ма Дар Гита"

5 минут от м.Новослободская/Достоевская

Доступны два зала для аренды:
- Большой (50 кв м)
- Маленький (10 кв м).

Студия в самом центре Москвы, тихая(!), уютная, с высокими потолками (3 м), серые стены идеальны для съемок, есть бесплатная стихийная парковка у входа.
Студия оборудована всем необходимым для практик, семинаров, конференций, мастер-классов:

- коврики (16 шт)
- подушки, одеяла
- мат для массажа 2х2 метра
- тайцзи бан для цигун
- ролики для МФР (6 шт)
- стулья (20 шт)
- белая стена для проектора
- проектор (+1000 ₽)
- флипчарт
- планшеты для бумаги А4
- bluetooth колонка
- штатив для телефона
- вода, чай
- с/у на этаже

Большой зал, 50 кв м.
Цены на аренду:
- будни до 18:00 - 800 р/60 мин,
- будни после 18:00 и выходные - 1300 р/60 мин.

Маленький зал, 10 кв м.
Цена на аренду:
- 500 р/60 мин

⚡При аренде большого зала длительностью от 4 часов - малый зал в подарок, то есть вся студия ваша ) ⚡

Правила брони и оплаты:
- Для брони предоплата 50%
- Вторая часть может быть оплачена день в день

Правила отмены:
- при аренде более 4 часов: полный возврат средств за 2 недели до аренды, позднее - 30 % остаётся студии
- при аренде менее 4 часов: полный возврат средств за 2 дня до аренды, позднее - 30 % остаётся студии
"""

        self.markup = self.__make_markup(db)
        self.__init_handlers(bot)

    def __make_markup(self, db):
        markup = InlineKeyboardMarkup()
        markup.add(
            InlineKeyboardButton("Начать диалог с администратором", callback_data="Чат"))
        markup.add(InlineKeyboardButton("Контакты", callback_data="Контакты"))
        markup.add(InlineKeyboardButton("В главное меню", callback_data="Главное меню"))
        return markup

    def __init_handlers(self, bot: TeleBot):
        @bot.callback_query_handler(func=lambda call: call.data == self.call_data)
        def cb(call: types.CallbackQuery):
            bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=self.text,
                                  reply_markup=self.markup, parse_mode="HTML")

        @bot.message_handler(commands=self.commands)
        def message(msg: types.Message):
            bot.send_message(chat_id=msg.chat.id, text=self.text,
                             reply_markup=self.markup, parse_mode="HTML")


t = int(input()) + 1
for case in range(1, t):
    n = int(input())
    m = []
    k, r, c = 0, 0, 0
    for i in range(n):
        m += [int(x) for x in input().split()]
        k += m[n * i + i]
    for i in range(n):
        start = i * n
        end = i * n + n
        if len(set(m[start:end])) != n:
            r += 1
        col = [m[x+i] for x in range(0, n**2, n)]
        if len(set(col)) != n:
            c += 1
    print("Case #%d: %d %d %d" % (case, k, r, c))


def sun_angle(time):
    import datetime as dt

    d_1 = dt.datetime.strptime("6:00", "%H:%M")
    d_2 = dt.datetime.strptime("18:00", "%H:%M")

    # 入力文字列の時間型datetimeへの変換
    time = dt.datetime.strptime(time, "%H:%M")

    if time < d_1 or time > d_2:
        return "I don't see the sun!"
    #datetime.timedelta.secondsで引き算の結果を秒で取り出し、角度/secで演算する
    ans = ((time - d_1).seconds) * (180 / 43200)
    return ans

if __name__ == '__main__':
    print("Example:")
    print(sun_angle("07:00"))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert sun_angle("07:00") == 15
    assert sun_angle("01:23") == "I don't see the sun!"
    print("Coding complete? Click 'Check' to earn cool rewards!")


import os
import time
import argparse
import numpy as np
import pandas as pd

from utils import timer, load_and_preprocess

def create_submission(X_train, y_train, X_test, df_test, thres, module):
    """
    train model with entire training data, predict test data,
    and create submission file

    Parameters
    ----------
    X_train, y_train, X_test: features and targets

    df_test: dataframe, test data

    thres: float, a decision threshold for classification

    module: a python module

    Return
    ------
    df_summission
    """
    # get model
    model = module.get_model()
    # train model
    print('fitting model')
    model = model.fit(X_train, y_train)
    # predict
    print('predicting probas')
    y_pred = np.squeeze(model.predict_proba(X_test) > thres).astype('int')
    # create submission file
    return pd.DataFrame({'qid': df_test.qid, 'prediction': y_pred})

def parse_args():
    parser = argparse.ArgumentParser(
        prog="Quora Insincere Questions Classification",
        description="Create Submission")
    parser.add_argument('--datapath', nargs='?', default=os.environ['DATA_PATH'],   # noqa
                        help='input data path')
    parser.add_argument('--model', nargs='?', default='model_v30',
                        help='model version')
    parser.add_argument('--thres', type=float, default=0.35,
                        help='decision threshold for classification')
    return parser.parse_args()

if __name__ == '__main__':
    # config
    # SHUFFLE = True
    # get args
    args = parse_args()
    datapath = args.datapath
    model = args.model
    best_thres = args.thres

    t0 = time.time()
    # 1. import module
    module = __import__(model)
    # 2. load and preprocess data
    with timer("Load and Preprocess"):
        df_train, df_test, X_train, X_test = load_and_preprocess(datapath, module)  # noqa
    # 3. create submission file
    with timer('Trainning and Creating Submission'):
        filepath = os.path.join(datapath, 'submit_' + model + '.csv')
        df_submission = create_submission(
            X_train, df_train.target,
            X_test, df_test,
            best_thres, module)
        df_submission.to_csv(filepath, index=False)
        print('Save submission file to {}'.format(filepath))
    # record time spent
    print('Entire program is done and it took {:.2f}s'.format(time.time() - t0)) # noqa


'''
This command will make multiple folders inside the given path
'''

import os
import sys
import argparse

desp = "Arguments description"

# Initialize parser
parser = argparse.ArgumentParser(description=desp)

# Adding optional argument
parser.add_argument("-d", "--directory", help="Parent directory path")
parser.add_argument("-n", "--number", help="Number of folders")
parser.add_argument("-p", '--phrase', help="Initial phrase for folder name")
parser.add_argument("-s", '--start', help="number to start with (default is 1)")
parser.add_argument("-v", "--verbose", help="Print output. Default is 0")

args = parser.parse_args()

DIR = args.directory
NUM = int(args.number)
PHRASE = args.phrase
if args.verbose:
    VERBOSE = int(args.verbose)
else:
    VERBOSE = 0
if(args.start):
    START = int(args.start)
else:
    START = 1

for i in range(NUM):
    file_name = PHRASE+str(i+START)
    temp  = os.system("mkdir %s" % file_name)
    if(VERBOSE):
        print(file_name, "created.")


import cv2
import numpy as np

#custom module
from src.basic import imageInfo

#Coding Section
###############################
image = cv2.imread(imageInfo.photographyImage)

B, G, R = image[50,0]
print(image.shape)
print(B,G,R)

#convert to grayscale and see what happens
grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

print(grayImage.shape)
print(grayImage[50,0])

#Convert to hsv image
hsvImage = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

cv2.imshow('Hsv image', hsvImage)
cv2.imshow('Hue channel', hsvImage[:,:,0])
cv2.imshow('Saturation channel', hsvImage[:,:,1])
cv2.imshow('Value channel', hsvImage[:,:,2])

print('Hsv shape : ' ,hsvImage.shape)

cv2.waitKey()
cv2.destroyAllWindows()


from Crypto import hash_str

class Transaction:

    nonce = None
    data = None
    to = None
    value = None
    sender = None
    fee = 0
    tx_hash = None

    def __init__(self, sender, to, value, nonce, fee=0, data=None):
        self.sender = sender
        self.to = to
        self.value = value
        self.fee = fee
        self.nonce = nonce
        self.data = data
        self.get_hash()

    def get_hash(self):
        str_to_hash = f"{self.sender}{self.to}{self.value}{self.fee}{self.nonce}{self.data}"
        self.tx_hash = hash_str(str_to_hash)

    def to_string(self):
        print(f"Tx..... {self.tx_hash}")
        print(f"To..... {self.to}")
        print(f"From... {self.sender}")
        print(f"Value.. {self.value}")
        print(f"Nonce.. {self.nonce}")
        print(f"Fee.... {self.fee}")
        print(f"Data... {self.data}\n")


import time

link = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"

def test_guest_should_see_basket_button(browser):
    browser.get(link)
    button = browser.find_element_by_id("add_to_basket_form")
    assert button is not None, 'The button is absent'


import random
from bingo import *
from constants import carton as cart
from carton import *
user_cart_long = int(input("Select the carton Long:"))
class Engine:
    __carton = cart()
    def __init__(self) -> None:
        self.__carton = list(map(lambda x: str(x), random.choice(cart()), Carton.get_long(user_cart_long)))
        self.__origin = self.__carton.copy()
        print(self.__origin)
        self._bomboNumbers = cart

    def show_carton(self):
        carton=self._origin if origin else self._carton
        for i in range (0, len[carton], 4):
            print(carton[i:i+4])
    def get_bombo_number(self):
        numeroPos=random.choice(cart()-1)
        pick = self._bomboNumbers[numeroPos]
        del self._bomboNumbers[numeroPos]
        self._pickedNumber.append(pick)
        return pick

Engine().show_carton


import os
import sys
from urllib.parse import urlparse

from bot import errors
from bot.player.enums import TrackType
from bot.player.track import Track

class Streamer:
    def __init__(self, service_manager):
        self.allowed_schemes = ['http', 'https', 'rtmp', 'rtsp']
        self.service_manager = service_manager

    def get(self, url, is_admin):
        parsed_url = urlparse(url)
        if parsed_url.scheme in self.allowed_schemes:
            track = Track(url=url, type=TrackType.Direct)
            fetched_data = [track]
            for service in self.service_manager.available_services.values():
                try:
                    if parsed_url.hostname in service.hostnames or service.name == self.service_manager.fallback_service:
                        fetched_data = service.get(url)
                        break
                except errors.ServiceError:
                    continue
                except:
                    if service.name == self.service_manager.fallback_service:
                        return [track, ]
            if len(fetched_data) == 1 and fetched_data[0].url.startswith(track.url):
                return [track, ]
            else:
                return fetched_data
        elif is_admin:
            if os.path.isfile(url):
                track = Track(url=url, name=os.path.split(url)[-1], format=os.path.splitext(url)[1], type=TrackType.Local)
                return [track, ]
            elif os.path.isdir(url):
                tracks = []
                for path, dirs, files in os.walk(url):
                    for file in sorted(files):
                        url = os.path.join(path, file)
                        name = os.path.split(url)[-1]
                        format = os.path.splitext(url)[1]
                        track = Track(url=url, name=name, format=format, type=TrackType.Local)
                        tracks.append(track)
                return tracks
            else:
                raise errors.PathNotFoundError('')
        else:
            raise errors.IncorrectProtocolError('')


def solution(n,red,blue):
     red_path=[set() for i in range(n)]
     blue_path=[set() for i in range(n)]
     for beg,end in red:
         red_path[beg].add(end)
     for beg,end in blue:
         blue_path[beg].add(end)
     dist=[[-1]*n for _ in range(2)]#dist[0]为红蓝红顺序找到的最短距离，dist[1]为蓝红蓝找到的最短距离
     dist[0][0]=0
     dist[1][0]=0
     now_red=[0]
     now_blue=[0]#index
     steps=0
     while len(now_red)!=0 or len(now_blue)!=0:
         nxt_lvl_red=[]
         next_lvl_blue=[]
         steps+=1
         if now_red:
             for beg in now_red:
                 ends_in_blue=blue_path[beg]
                 if len(ends_in_blue)==0:
                     continue
                 for end in ends_in_blue:
                     if dist[0][end]==-1:
                         dist[0][end]=steps
                         next_lvl_blue.append(end)
         if now_blue:
             for beg in now_blue:
                 ends_in_red=red_path[beg]
                 if len(ends_in_red)==0:
                     continue
                 for end in ends_in_red:
                     if dist[1][end]==-1:
                         dist[1][end]=steps
                         nxt_lvl_red.append(end)
         now_blue=next_lvl_blue
         now_red=nxt_lvl_red

     res=[-1]*n
     for i in range(n):
         res[i]=max(dist[1][i],dist[0][i])
     return  res

if __name__=="__main__":
     n=int(input())
     red=eval(input())
     blue=eval(input())
     res=solution(n,red,blue)
     print(res)


import paddle
import paddle.nn.functional as F
import paddle.nn as nn
import numpy as np

class HED(nn.Layer):
    '''
    HED网络结构为VGG16删去后面的全连接层和softmax层
    包括5个stage：
    stage1由2个卷积和1个MaxPooling构成，每个卷积后接一个ReLU
    stage2由3个卷积和1个MaxPooling构成，每个卷积后接一个ReLU
    stage3由3个卷积和1个MaxPooling构成，每个卷积后接一个ReLU
    stage4由3个卷积和1个MaxPooling构成，每个卷积后接一个ReLU
    stage5由3个卷积和1个MaxPooling构成，每个卷积后接一个ReLU
    '''
    def __init__(self):
        super(HED, self).__init__()
        '''stage1'''
        self.conv1_1 = nn.Conv2D(3, 64, 3, padding=1)
        self.conv1_2 = nn.Conv2D(64, 64, 3, padding=1)

        '''stage2'''
        self.conv2_1 = nn.Conv2D(64, 128, 3, padding=1)
        self.conv2_2 = nn.Conv2D(128, 128, 3, padding=1)

        '''stage3'''
        self.conv3_1 = nn.Conv2D(128, 256, 3, padding=1)
        self.conv3_2 = nn.Conv2D(256, 256, 3, padding=1)
        self.conv3_3 = nn.Conv2D(256, 256, 3, padding=1)

        '''stage4'''
        self.conv4_1 = nn.Conv2D(256, 512, 3, padding=1)
        self.conv4_2 = nn.Conv2D(512, 512, 3, padding=1)
        self.conv4_3 = nn.Conv2D(512, 512, 3, padding=1)

        '''stage5'''
        self.conv5_1 = nn.Conv2D(512, 512, 3, padding=1)
        self.conv5_2 = nn.Conv2D(512, 512, 3, padding=1)
        self.conv5_3 = nn.Conv2D(512, 512, 3, padding=1)

        self.relu = nn.ReLU()
        self.maxpool = nn.MaxPool2D(2, stride=2, ceil_mode=True)

        self.branch1 = nn.Conv2D(64, 1, 1)
        self.branch2 = nn.Conv2D(128, 1, 1)
        self.branch3 = nn.Conv2D(256, 1, 1)
        self.branch4 = nn.Conv2D(512, 1, 1)
        self.branch5 = nn.Conv2D(512, 1, 1)
        self.score_final = nn.Conv2D(5, 1, 1)

        self.sigmoid = nn.Sigmoid()

        # self.deconv2 = nn.Conv2DTranspose(1,1,3,2)
        # self.deconv3 = nn.Conv2DTranspose(1,1,4,4)
        # self.deconv4 = nn.Conv2DTranspose(1,1,8,8)
        # self.deconv5 = nn.Conv2DTranspose(1,1,16,16)

        # self.proconv2 = nn.Conv2D(1,1,3,1,1)
        # self.proconv3 = nn.Conv2D(1,1,3,1,1)
        # self.proconv4 = nn.Conv2D(1,1,3,1,1)
        # self.proconv5 = nn.Conv2D(1,1,3,1,1)

        for m in self.sublayers():
            if isinstance(m, nn.Conv2D):
                n = m.weight.shape[0] * m.weight.shape[1] * m.weight.shape[2]
                v = np.random.normal(loc=0., scale=np.sqrt(2. / n), size=m.weight.shape).astype('float32')
                m.weight.set_value(v)

    def forward(self,x):
        '''
        :param x.shape:(Batch_size,Channel,Height,Weight)
        :return: y.shape:(Batch_size,1,Height,Weight)
        '''
        img_H, img_W = x.shape[2], x.shape[3]
        '''VGG16的前13个阶段'''
        '''stage1'''
        conv1_1 = self.relu(self.conv1_1(x))
        conv1_2 = self.relu(self.conv1_2(conv1_1))  # batch_size,64,H,W
        pool1 = self.maxpool(conv1_2)

        '''stage2'''
        conv2_1 = self.relu(self.conv2_1(pool1))
        conv2_2 = self.relu(self.conv2_2(conv2_1))  # batch_size,128,H/2,W/2
        pool2 = self.maxpool(conv2_2)

        '''stage3'''
        conv3_1 = self.relu(self.conv3_1(pool2))
        conv3_2 = self.relu(self.conv3_2(conv3_1))
        conv3_3 = self.relu(self.conv3_3(conv3_2))  # batch_size,256,H/4,W/4
        pool3 = self.maxpool(conv3_3)

        '''stage4'''
        conv4_1 = self.relu(self.conv4_1(pool3))
        conv4_2 = self.relu(self.conv4_2(conv4_1))
        conv4_3 = self.relu(self.conv4_3(conv4_2))  # batch_size,512,H/8,W/8
        pool4 = self.maxpool(conv4_3)

        '''stage5'''
        conv5_1 = self.relu(self.conv5_1(pool4))
        conv5_2 = self.relu(self.conv5_2(conv5_1))
        conv5_3 = self.relu(self.conv5_3(conv5_2))  # batch_size,512,H/16,W/16 (14)

        '''每个stage对应的分支'''
        # b1 = self.relu(self.branch1(conv1_2))  # batch_size,1,H,W
        # b2 = self.relu(self.branch2(conv2_2))  # batch_size,1,H/2,W/2
        # b3 = self.relu(self.branch3(conv3_3))  # batch_size,1,H/4,W/4
        # b4 = self.relu(self.branch4(conv4_3))  # batch_size,1,H/8,W/8
        # b5 = self.relu(self.branch5(conv5_3))  # batch_size,1,H/16,W/16
        b1 = self.branch1(conv1_2)  # batch_size,1,H,W
        b2 = self.branch2(conv2_2)  # batch_size,1,H/2,W/2
        b3 = self.branch3(conv3_3)  # batch_size,1,H/4,W/4
        b4 = self.branch4(conv4_3)  # batch_size,1,H/8,W/8
        b5 = self.branch5(conv5_3)  # batch_size,1,H/16,W/16

        '''每个分支进行线性插入（上采样），第一个分支不用，因为其就是原图的长宽'''
        b2 = F.interpolate(b2, size=[img_H,img_W], mode='bilinear')      # 也可使用nn.functional.conv2d_transpose转置卷积
        b3 = F.interpolate(b3, size=[img_H,img_W], mode='bilinear')
        b4 = F.interpolate(b4, size=[img_H,img_W], mode='bilinear')
        b5 = F.interpolate(b5, size=[img_H,img_W], mode='bilinear')
        # b2 = F.conv2d_transpose()
        # b2 = self.deconv2(b2)
        # b3 = self.deconv3(b3)
        # b4 = self.deconv4(b4)
        # b5 = self.deconv5(b5)

        # print(b2.shape,b3.shape,b4.shape,b5.shape)
        # print(x.shape[0])
        b2 = paddle.crop(b2,shape=(1,1,img_H,img_W))
        b3 = paddle.crop(b3,shape=(1,1,img_H,img_W))
        b4 = paddle.crop(b4,shape=(1,1,img_H,img_W))
        b5 = paddle.crop(b5,shape=(1,1,img_H,img_W))

        # b2 = self.proconv2(b2)
        # b3 = self.proconv2(b3)
        # b4 = self.proconv2(b4)
        # b5 = self.proconv2(b5)

        '''连接每一个分支'''
        fusecat = paddle.concat([b1, b2, b3, b4, b5], axis=1)
        fuse = self.score_final(fusecat)
        results = [b1, b2, b3, b4, b5, fuse]
        results = [self.sigmoid(r) for r in results]
        return results

if __name__ == '__main__':
    net = HED()
    x = paddle.rand((1,3,224,224))
    y = net(x)
    for i in y:
        print(i.shape)


# Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def increasingBST(self, root: TreeNode) -> TreeNode:
        self.res=[]
        A=TreeNode()
        self.temp=A
        def inOrder(node):
            if node:
                inOrder(node.left)
                self.res.append(node.val)
                inOrder(node.right)
        inOrder(root)
        A=TreeNode(self.res[0])
        temp=A
        i=1
        while i<len(self.res):
            temp.right=TreeNode(self.res[i])
            temp=temp.right
            i+=1
        return A


import random

class Board:
    def __init__(self):
        self.board = [['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9']]

    def in_action(self, place, do):
        self.board[place].append(do)

        return board

    def step(self):
        count = 0
        for i in self.board:
            print(i, end='')
            count += 1
            if count == 3:
                print('')
                count = 0

    def brake_system(self, player):
        bord = ''
        for i in self.board:
            for j in i:
                bord += j
        if bord[0:3] == player.xo * 3 or bord[3:6] == player.xo * 3 or bord[6:] == player.xo * 3 or bord[0::4] == player.xo * 3 or bord[2:7:2] == player.xo or bord[0:8:3] == player.xo * 3 or bord[1:9:3] == player.xo * 3 or bord[2::3] == player.xo * 3:
            return True
        elif '1' and '2' and '3' and '4' and '5' and '6' and '7' and '8' and '9' not in bord:
            print('Ничья!\n')
            self.board = [['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9']]

class Player:
    def __init__(self, xo):
        self.name = 'Игрок'
        self.xo = xo
        self.board = Board()

    def do(self, doit, board, name):
        board[doit - 1] = [name]
        #board.board[]

class Ai:
    def __init__(self, player):
        self.name = 'Компьютер'
        self.xo = 'o'
        self.enemy = player

    def doai(self, board):
        rand = random.randint(0, 8)
        while True:
            if board[rand] != ['x'] and board[rand] != ['o']:
                board[rand] = ['o']
                break
            else:
                rand = random.randint(0, 8)

def play(player_1, player_2, board):
    board.step()
    while True:
        print(f'Ходит игрок рисующий {player_1.xo}')
        try:
            player_1.do(int(input('Куда ставим крестик?: ')), board.board, player_1.xo)
        except ValueError:
            print('Пропуск хода. Да именно так')
        board.step()

        if board.brake_system(player_1):
            print(f'Победил {player_1.name} {player_1.xo}\n')
            break

        if player_2.name == 'Игрок':
            print(f'Ходит игрок рисующий {player_2.xo}')
            try:
                player_2.do(int(input('Куда ставим нолик?: ')), board.board, player_2.xo)
            except ValueError:
                print('Пропуск хода. Да именно так')
        elif player_2.name == 'Компьютер':
            print('Ходит Суперкомпьютер')
            player_2.doai(board.board)
        if board.brake_system(player_2):
            print(f'Победил {player_2.name} {player_2.xo}\n')
            break
        board.step()

board = Board()
player_1 = Player('x')
player_2 = Player('o')
comp = Ai(player_1)

print('Игра крестики-нолики\n(клетки слева направо-сверху вниз), для хода нужно ввести цифру')
ask = input('Будем играть вдвоем или с компьютером? (2/1): ')
if ask == '1':
    play(player_1, comp, board)
elif ask == '2':
    play(player_1, player_2, board)


def lengthOfLongestSubstring(self, s):
    """
    :type s: str
    :rtype: int
    """
    start,end,max_len = 0,0,0
    map = {}
    while start < len(s) and end < len(s):
        if s[end] in map.keys():
            # 这里的man(start.....)保证了start不会往回倒退
            start = max(start, map[s[end]] + 1)
        map[s[end]] = end
        max_len = max(max_len, end - start + 1)
        end += 1
    return max_len


import math
nums = input()[1:-1].split(',')
H = int(input())
count = 0
for i in range(0, len(nums)):
    nums[i] =int(nums[i])
    count +=nums[i]
n = len(nums)
least = math.ceil(count/H)

while True:
    time =0
    for i in range(0,n):
        time += math.ceil(nums[i]/least)
    if time <=H:
        break
    least+=1

print(least)


#!/usr/bin/python3
def weight_average(my_list=[]):
    if my_list is not None:
        total = 0
        frequency = 0
        for tup in my_list:
            (weight, occurrence) = tup
            total += weight * occurrence
            frequency += occurrence
        result = total / frequency if frequency > 0 else 0
        return result
    else:
        return 0


"""
从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果：
[
  [3],
  [9,20],
  [15,7]
]
提示：节点总数 <= 1000
"""

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

class Solution(object):
    # 思路：
    #   层序遍历，套用模板，百试不爽。
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        ans = []
        stack = [root]
        # 外层while遍历树的层数
        while stack:
            temp = []
            sizeStack = len(stack)
            # 内层for遍历每一层（当前层）的所有节点
            for i in range(sizeStack):
                node = stack.pop(0)
                temp.append(node.val)
                if node.left:
                    stack.append(node.left)
                if node.right:
                    stack.append(node.right)
            ans.append(temp)
        return ans

剑指offer题/剑指 Offer 32 - II. 从上到下打印二叉树 II.py


import torch

from sutra.model.lm.rnn_lm import RNNLanguageModel, RNNLanguageModelConfig
from sutra.model.lm.transformer_lm import TransformerLanguageModel, TransformerLanguageModelConfig
from sutra.model.lm.linear_lm import LinearLanguageModel, LinearLanguageModelConfig
from sutra.model.lm.trainer import train_language_model
from sutra.trainer import TrainingConfig, Stage

from test.utils import create_batch
from test.asserts import assert_non_zero

def check_can_overfit(model_config, batched_iterator):
    # Check the model can make loss small on very small data

    training_config = TrainingConfig(
        epoch_length=100,
        max_epochs=1,
        batch_size=4,
        optimizer='adam',
        # High learning rate as tests should be fast
        learning_rate=0.01,
        device='cpu')

    class DummyDataset:
        train_data = list(range(20))
        valid_data = list(range(20))

    dataset = DummyDataset()

    trainer = train_language_model(model_config,
                                   training_config,
                                   dataset,
                                   batched_iterator)

    df = trainer.metrics.data
    df = df[df.stage == Stage.VALIDATION]
    df = df[df.epoch == training_config.max_epochs]
    loss = sum(df.loss) / len(df)

    assert loss < 0.1

def check_gradients(model, batched_iterator):

    # Run over a single batch and check loss and gradients aren't
    # totally wrong

    batch_size = 2
    if batched_iterator:
        batch = create_batch([[0, 10],
                              [1, 11],
                              [2, 12],
                              [3, 13]],
                             [[1, 11],
                              [2, 12],
                              [3, 13],
                              [4, 14]])
    else:
        batch = create_batch([[0, 10],
                              [1, 11],
                              [2, 12],
                              [3, 13]],
                             [4, 14])

    state = model.init_state(batch_size)
    output, state = model(batch.data, state)
    cross_entropy = torch.nn.CrossEntropyLoss()

    # loss is non-zero
    loss = model.calculate_loss(output, batch.target, cross_entropy)
    assert loss != 0

    # Gradients are non-zero
    loss.backward()
    for param in model.parameters():
        if param.requires_grad:
            assert param.grad is not None
            assert_non_zero(param.grad)

def test_linear_language_model():

    config = LinearLanguageModelConfig(
        vocab_size=24,
        seq_length=4,
        embedding_size=16,
        encoding_size=16,
        dropout_prob=0.0)

    model = LinearLanguageModel.from_config(config, 'cpu')

    check_gradients(model, batched_iterator=False)
    check_can_overfit(config, batched_iterator=False)

def test_rnn_language_model():

    config = RNNLanguageModelConfig(
        vocab_size=24,
        seq_length=4,
        embedding_size=16,
        encoding_size=16,
        num_layers=1,
        dropout_prob=0.0)

    model = RNNLanguageModel.from_config(config, 'cpu')

    check_gradients(model, batched_iterator=True)
    check_can_overfit(config, batched_iterator=True)

def test_transformer_language_model():
    config = TransformerLanguageModelConfig(
        vocab_size=24,
        seq_length=4,
        embedding_size=16,
        encoding_size=16,
        num_attention_heads=1,
        num_layers=2,
        dropout_prob=0.0)

    model = TransformerLanguageModel.from_config(config, 'cpu')

    check_gradients(model, batched_iterator=False)
    check_can_overfit(config, batched_iterator=False)


'''
URL = https://leetcode.com/problems/calculate-digit-sum-of-a-string/
2243. Calculate Digit Sum of a String
Easier to process as a list of ints instead
'''
class Solution:
    def digitSum(self, s: str, k: int) -> str:
        digList = []
        for letter in s:
            digList.append(int(letter))
        # Strings immutable : leverage a temp copy space / buffer
        while(len(digList) > k):
            tempList = []
            digListPtr = 0
            kGroupSum = 0
            curGroupSize = 0
            while(digListPtr < len(digList)):
                kGroupSum += digList[digListPtr]
                curGroupSize += 1
                if(curGroupSize == k):
                    self.insertValIntoTempList(tempList,kGroupSum)
                    kGroupSum = 0
                    curGroupSize = 0
                digListPtr += 1
            # final run sum again ( based on kCount val too )
            if(curGroupSize > 0):
                self.insertValIntoTempList(tempList,kGroupSum)
            digList.clear()
            digList.extend(tempList) # faster than append()
        finalS = ''.join([str(digit) for digit in digList])
        return finalS

    def insertValIntoTempList(self, tempList:List[int],kGroupSum:int) -> None:
        if(kGroupSum == 0):
            tempList.append(0)
            return
        listToRev = []
        while(kGroupSum > 0):
            rem = kGroupSum % 10
            listToRev.append(rem)
            kGroupSum = int(kGroupSum / 10)
        if(kGroupSum > 0):
            listToRev.append(kGroupSum)
        listToRev.reverse()
        for x in listToRev:
            tempList.append(x)


# Giselle Northy
# CS 372 Fall 2020
# Project 1
# Part 1 Use a socket to GET a file
# File: connect_socket_proj1_part_1.py
# Version: Python3.7
#
# Sources:
# A. Computer Networking - A Top-Down Approach, Kurose and Ross, 7th Edition
# B. https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
# C. Sockets Tutorial with Python 3 part 2 - buffering and streaming data
#    https://www.youtube.com/watch?v=8A4dqoGL62E
# D. Sockets Tutorial with Python 3 part 1 - sending and receiving data
#    https://www.youtube.com/watch?v=Lbfe3-v7yE0

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = "gaia.cs.umass.edu"

# connect to server
s.connect((server, 80))

#send GET request to server....
get_request = "GET /wireshark-labs/INTRO-wireshark-file1.html HTTP/1.1\r\nHost:gaia.cs.umass.edu\r\n\r\n"
print("Request: " + get_request)
s.send(get_request.encode())

# get message from server
msg = s.recv(1024)
print("[RECV] - length: " + str(len(msg)))
print(msg.decode())


from infomap              import Infomap
from src.mapsim           import MapSim
from src.mapsim.io.reader import NetworkFromNetFile

def test_read_treefile():
    im = Infomap( silent    = True
                , two_level = True
                , seed      = 42
                )

    net = NetworkFromNetFile( filename = "examples/coding-example.net"
                            , directed = False
                            )

    for (u,v,_w) in net.get_edges():
        im.add_link(u,v)

    im.run()
    im.write_tree("out/tmp.tree")

    #pc = MapSim().from_treefile("out/tmp.tree")

    #assert len(pc.addresses) == 9
    assert(True)


#A binary gap is the largest amount of consecutive 0s on a binary number.
def binary_gap ( N ):
  b = bin(N)
  b =  b[2:] #Take away the 0b from string
  b = b.rstrip('0') #If ends on 0 all 0s before doesn`t form a gap
  gaps = b.split('1') #Takes all gaps
  maxGap = 0
  for gap in gaps:
     maxGap = len(gap) if len(gap) > maxGap else maxGap #Find max Gap
  return maxGap