from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]

def main():
    # Credentials Check
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)

        service = build("calendar", "v3", credentials=creds)

        # Call the Calendar API and get the list of Calendars for the user account
        colors = service.colors().get().execute()

        # Print available calendarListEntry colors.
        for id, color in colors['calendar'].iteritem():
            print ('colorId: %s' % id)
            print ('  Background: %s' % color['background'])
            print ('  Foreground: %s' % color['foreground'])
        # Print available event colors.
        for id, color in colors['event'].iteritem():
            print ('colorId: %s' % id)
            print ('  Background: %s' % color['background'])
            print ('  Foreground: %s' % color['foreground'])

if __name__ == "__main__":
    main()


"""
This script will find the generative noise model parameters that create mock lightcurves matching the data properties in term of gaussian and correlated noise
You can also provide directly the correct parameters in the config file. In this case I will just generate the python files to proceed to the step 3b and 3c
and skip the optimisation
"""
import matplotlib
matplotlib.use('Agg')
import os
import pycs3.sim.draw
import pycs3.gen.util
import pycs3.gen.splml
import pycs3.sim.twk as twk
import pycs3.spl.topopt
import pycs3.pipe.optimiser
import pycs3.pipe.pipe_utils as ut
import sys
import argparse as ap
import importlib
import logging
loggerformat='PID %(process)06d | %(asctime)s | %(levelname)s: %(name)s(%(funcName)s): %(message)s'
logging.basicConfig(format=loggerformat,level=logging.INFO)

def run_DIC(lcs, spline, fit_vector, kn, ml, optim_directory, config_file, stream, tolerance=0.75):
    config = importlib.import_module(config_file)
    pycs3.sim.draw.saveresiduals(lcs, spline)
    print("I'll try to recover these parameters :", fit_vector)
    dic_opt = pycs3.pipe.optimiser.DicOptimiser(lcs, fit_vector, spline, config.attachml, ml, knotstep=kn,
                                                savedirectory=optim_directory,
                                                recompute_spline=True, max_core=config.max_core,
                                                n_curve_stat=config.n_curve_stat,
                                                shotnoise=config.shotnoise_type, tweakml_type=config.tweakml_type,
                                                tweakml_name=config.tweakml_name, display=config.display, verbose=False,
                                                correction_PS_residuals=True, max_iter=config.max_iter, tolerance=tolerance,
                                                theta_init=None)

    chain = dic_opt.optimise()
    dic_opt.analyse_plot_results()
    chi2, B_best = dic_opt.get_best_param()
    A = dic_opt.A_correction
    dic_opt.reset_report()
    dic_opt.report()

    if dic_opt.success:
        print("I succeeded finding a parameter falling in the %2.2f sigma from the original lightcurve." % tolerance)

    else:
        print("I didn't find a parameter that falls in the %2.2f sigma from the original lightcurve." % tolerance)
        print("I then choose the best one... but be carefull ! ")

    for k in range(len(lcs)):
        def tweakml_PS_NUMBER(lcs, spline):
            return twk.tweakml_PS(lcs, spline, B_PARAM, f_min=1 / 300.0, psplot=False, verbose=False,
                                  interpolation='linear', A_correction=A_PARAM)

        ut.write_func_append(tweakml_PS_NUMBER, stream,
                             B_PARAM=str(B_best[k][0]), NUMBER=str(k + 1), A_PARAM=str(A[k]))

def main(lensname, dataname, work_dir='./'):
    sys.path.append(work_dir + "config/")
    config_file = "config_" + lensname + "_" + dataname
    config = importlib.import_module(config_file)
    tweakml_plot_dir = config.figure_directory + 'tweakml_plots/'
    optim_directory = tweakml_plot_dir + 'twk_optim_%s_%s/' % (config.optimiser, config.tweakml_name)

    if not os.path.isdir(tweakml_plot_dir):
        os.mkdir(tweakml_plot_dir)

    if config.mltype == "splml":
        if config.forcen:
            ml_param = config.nmlspl
            string_ML = "nmlspl"
        else:
            ml_param = config.mlknotsteps
            string_ML = "knml"
    elif config.mltype == "polyml":
        ml_param = config.degree
        string_ML = "deg"
    else:
        raise RuntimeError('I dont know your microlensing type. Choose "polyml" or "spml".')

    for i, kn in enumerate(config.knotstep):
        for j, ml in enumerate(ml_param):
            f = open(config.lens_directory + config.combkw[i, j] + '/tweakml_' + config.tweakml_name + '.py', 'w+')
            f.write('import pycs3 \n')
            f.write('from pycs3.sim import twk as twk \n')
            lcs, spline = pycs3.gen.util.readpickle(config.lens_directory + '%s/initopt_%s_ks%i_%s%i.pkl' % (
            config.combkw[i, j], dataname, kn, string_ML, ml))
            fit_vector = pycs3.pipe.optimiser.get_fit_vector(lcs, spline)  # we get the target parameter now
            if not os.path.isdir(optim_directory):
                os.mkdir(optim_directory)

            # We need spline microlensing for tweaking the curve, if it is not the case we change it here to a flat spline that can be tweaked.
            # the resulting mock light curve will have no ML anyway, we will attach it the ML defined in your config file before optimisation.
            polyml = False
            for k, l in enumerate(lcs):
                if l.ml == None:
                    print(
                        'I dont have ml, I have to introduce minimal extrinsic variation to generate the mocks. Otherwise I have nothing to modulate.')
                    pycs3.gen.splml.addtolc(l, n=2)
                elif l.ml.mltype == 'poly':
                    polyml = True
                    print(
                        'I have polyml and it can not be tweaked. I will replace it with a flat spline just for the mock light curve generation.')
                    l.rmml()

            if polyml:
                spline = pycs3.spl.topopt.opt_fine(lcs, nit=5, knotstep=kn,
                                                   verbose=False, bokeps=kn / 3.0,
                                                   stabext=100)  # we replace the spline optimised with poly ml by one without ml
                for l in lcs:
                    pycs3.gen.splml.addtolc(l, n=2)
                pycs3.gen.util.writepickle((lcs, spline),
                                           config.lens_directory + '%s/initopt_%s_ks%i_%s%i_generative_polyml.pkl' % (
                                           config.combkw[i, j], dataname, kn, string_ML, ml))

            # Starting to write tweakml function depending on tweak_ml_type :
            if config.tweakml_type == 'colored_noise':
                if config.shotnoise_type == None:
                    print('WARNING : you are using no shotnoise with the colored noise ! That will probably not work.')

                if config.find_tweak_ml_param == True:
                    raise NotImplementedError(
                        "I am not supporting automatic optimisation for colored_noise yet. You should provide your generative noise model parameter yourself or use PS_from_residuals.")
                else:
                    print("Colored noise : I will add the beta and sigma that you gave in input.")
                    for k in range(len(lcs)):
                        def tweakml_colored_NUMBER(lcs, spline):
                            return twk.tweakml(lcs, spline, beta=BETA, sigma=SIGMA, fmin=1.0 / 500.0, fmax=0.2,
                                               psplot=False)

                        ut.write_func_append(tweakml_colored_NUMBER, f,
                                             BETA=str(config.colored_noise_param[k][0]),
                                             SIGMA=str(config.colored_noise_param[k][1]), NUMBER=str(k + 1))

                list_string = 'tweakml_list = ['
                for k in range(len(lcs)):
                    list_string += 'tweakml_colored_' + str(k + 1) + ','
                list_string += ']'
                f.write('\n')
                f.write(list_string)

            elif config.tweakml_type == 'PS_from_residuals':
                if config.shotnoise_type != None:
                    print('If you use PS_from_residuals, the shotnoise should be set to None. I will do it for you !')
                    config.shotnoise_type = None

                if config.find_tweak_ml_param == True:
                    if config.optimiser == 'DIC':
                        run_DIC(lcs, spline, fit_vector, kn, ml, optim_directory, config_file, f)
                    else:
                        raise RuntimeError('I do not recognise your optimiser, please use DIC with PS_from_residuals')

                else:
                    print("Noise from Power Spectrum of the data : I use PS_param that you gave in input.")
                    for k in range(len(lcs)):
                        def tweakml_PS_NUMBER(lcs, spline):
                            return twk.tweakml_PS(lcs, spline, B_PARAM, f_min=1 / 300.0, psplot=False, verbose=False,
                                                  interpolation='linear')

                        ut.write_func_append(tweakml_PS_NUMBER, f,
                                             B_PARAM=str(config.PS_param_B[k]), NUMBER=str(k + 1))

                list_string = 'tweakml_list = ['
                for k in range(len(lcs)):
                    list_string += 'tweakml_PS_' + str(k + 1) + ','
                list_string += ']'
                f.write('\n')
                f.write(list_string)

            else:
                raise RuntimeError("I don't know your tweak_ml_type, please use colored_noise or PS_form_residuals.")
            f.close()
            # rename the file :
            files = [file for file in os.listdir(optim_directory)
                     if os.path.isfile(os.path.join(optim_directory, file)) and (string_ML not in file)]

            for file in files:
                prefix, extension = file.split('.')
                os.rename(os.path.join(optim_directory, file),
                          os.path.join(optim_directory, prefix + "_kn%i_%s%i." % (kn, string_ML, ml) + extension))

if __name__ == '__main__':
    parser = ap.ArgumentParser(prog="python {}".format(os.path.basename(__file__)),
                               description="Find the noise parameter to reproduce the data.",
                               formatter_class=ap.RawTextHelpFormatter)
    help_lensname = "name of the lens to process"
    help_dataname = "name of the data set to process (Euler, SMARTS, ... )"
    help_work_dir = "name of the working directory"
    parser.add_argument(dest='lensname', type=str,
                        metavar='lens_name', action='store',
                        help=help_lensname)
    parser.add_argument(dest='dataname', type=str,
                        metavar='dataname', action='store',
                        help=help_dataname)
    parser.add_argument('--dir', dest='work_dir', type=str,
                        metavar='', action='store', default='./',
                        help=help_work_dir)
    args = parser.parse_args()
    main(args.lensname, args.dataname, work_dir=args.work_dir)


import sys

fin = open(sys.argv[1])
fout = open(sys.argv[2], 'w')

for line in fin:
	name = line[12:16].strip()
	resname = line[17:20].strip()

	if name in ['N', 'C', 'O']:
		continue
	elif name == 'CA':
		if resname != 'GLY':
			continue
		# end if
	# end if

	fout.writelines(line)
# end for
fin.close()
fout.close()


from porE.hea.HEA import HEA
from pore import porosity as p
from pore import psd
from porE.io.ase2pore import *
# start from a cif file
cif = 'structures/cif/uio66_vesta.cif'
#
# Execute HEA, using the cif file
#
Phi_HEA = HEA(cif)[0]
# convertes cif to porE xyz (i.e., pypore.xyz)
ase2pore(cif)
structure = 'pypore.xyz'
#
# Execute porosity evaluation, using the overlapping sphere apporach (OSA)
#
print('-----------')
print('\nRun OSA\n')
print('-----------')
Phi, density, poreV, V_total, V_vdwSum, V_overlap = p.osa(structure)
#
# Execute an analyis of the pore size distribution (PSD)
# First number   -> Number of starting points
# Second number  -> Number of MC steps
#
print('-----------')
print('\nRun PSD\n')
print('-----------')
no_pores,tmp1,tmp2,tmp3,tmp4 = psd.get_psd(structure,200,1000)
pores           = tmp1[0:no_pores]
distr           = tmp2[0:no_pores]
pore_pos_cart   = tmp3[0:no_pores]
pore_pos_frac   = tmp4[0:no_pores]
#
# Execute porosity evaluation, using the grid point apporach (GPA)
# a probe radius for the accessible porosity needs to be provided
#
probe_R = 1.20
#
# Here, explicitly provide the full grid (grid points along each cell vector)
# FullGrid
grid_a = grid_b = grid_c = 30
print('-----------------------------------')
print('\nRun GPA: grid_a, grid_b, grid_c\n')
print('-----------------------------------')
Phi_void, Phi_acc, density, poreV_void, poreV_acc = p.gpa_fullgrid(structure,probe_R,grid_a,grid_b,grid_c)
#
# Here, a grid point density per A is provided instead
# GridPerA
grid_density = 2.0
print('-------------------------')
print('\nRun GPA: grid_density\n')
print('-------------------------')
Phi_void, Phi_acc, density, poreV_void, poreV_acc = p.gpa_gridpera(structure,probe_R,grid_density)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020-2021, Yoel Cortes-Pena <yoelcortes@gmail.com>
# Bioindustrial-Park: BioSTEAM's Premier Biorefinery Models and Results
# Copyright (C) 2021, Yalin Li <yalinli2@illinois.edu>
#
# Part of this module is based on the cornstover biorefinery:
# https://github.com/BioSTEAMDevelopmentGroup/Bioindustrial-Park/tree/master/BioSTEAM%202.x.x/biorefineries/cornstover
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt
# for license details.

import biosteam as bst
from biosteam import main_flowsheet as F
from biorefineries import (
    cornstover as cs,
    sugarcane as sc
    )

# from biorefineries.wwt import (
#     create_cs_chemicals,
#     cs_price, load_cs_settings,
#     create_wastewater_treatment_system,
#     get_cs_GWP,
#     )
# from biorefineries.utils import get_MESP
from _chemicals import create_cs_chemicals
from _settings import cs_price, load_cs_settings
from _wwt_sys import create_wastewater_treatment_system
from _lca import get_cs_GWP
from utils import get_MESP

# %%

# =============================================================================
# Function to make the system
# =============================================================================

load_cs_settings()
chems = create_cs_chemicals()
bst.settings.set_thermo(chems)

@bst.SystemFactory(
    ID='cornstover_sys',
    ins=[*cs.create_dilute_acid_pretreatment_system.ins,
          dict(ID='denaturant',
               Octane=1,
               price=cs_price['Denaturant'])],
    outs=[dict(ID='ethanol', price=cs_price['Ethanol'])],
)
def create_cs_system(ins, outs, include_blowdown_recycle=True, **wwt_kwargs):
    feedstock, denaturant = ins
    ethanol, = outs
    f = bst.main_flowsheet
    s = f.stream
    u = f.unit
    U101 = cs.FeedStockHandling('U101', feedstock)
    U101.cost_items['System'].cost = 0.

    pretreatment_sys = cs.create_dilute_acid_pretreatment_system(
        ins=U101-0,
        mockup=True
    )

    fermentation_sys = cs.create_cellulosic_fermentation_system(
        ins=pretreatment_sys-0,
        mockup=True,
    )

    ethanol_purification_sys = sc.create_ethanol_purification_system(
        ins=[fermentation_sys-1, denaturant],
        outs=[ethanol],
        IDs={'Beer pump': 'P401',
             'Beer column heat exchange': 'H401',
             'Beer column': 'D402',
             'Beer column bottoms product pump': 'P402',
             'Distillation': 'D403',
             'Distillation bottoms product pump': 'P403',
             'Ethanol-denaturant mixer': 'M701',
             'Recycle mixer': 'M402',
             'Heat exchanger to superheat vapor to molecular sieves': 'H402',
             'Molecular sieves': 'U401',
             'Ethanol condenser': 'H403',
             'Ethanol day tank': 'T701',
             'Ethanol day tank pump': 'P701',
             'Denaturant storage': 'T702',
             'Denaturant pump': 'P702',
             'Product tank': 'T703'},
        mockup=True,
    )
    ethanol, stillage, stripper_bottoms_product = ethanol_purification_sys.outs
    recycled_water = bst.Stream(Water=1,
                                T=47+273.15,
                                P=3.9*101325,
                                units='kg/hr')
    S401 = bst.PressureFilter('S401', (stillage, recycled_water))
    if include_blowdown_recycle:
        blowdown_to_wastewater = bst.Stream('blowdown_to_wastewater')
    else:
        blowdown_to_wastewater = None

    create_wastewater_treatment_system(
        ins=[S401-1, pretreatment_sys-1, blowdown_to_wastewater],
        outs=['biogas', 'sludge_S603', 'recycled_water', 'brine'],
        mockup=True,
        R601_kwargs={'method': 'lumped'},
        R602_kwargs={'HRT': 35},
        **wwt_kwargs,
    )

    M501 = bst.Mixer('M501', (u.S603-1, S401-0))

    cs.create_facilities(
        solids_to_boiler=M501-0,
        gas_to_boiler=s.biogas,
        process_water_streams=(s.stripping_water,
                               s.warm_process_water_1,
                               s.warm_process_water_2,
                               s.pretreatment_steam,
                               s.saccharification_water),
        feedstock=feedstock,
        RO_water=u.S604-0,
        recycle_process_water=stripper_bottoms_product,
        blowdown_to_wastewater=blowdown_to_wastewater,
    )

# %%

# =============================================================================
# Create the system
# =============================================================================

flowsheet = bst.Flowsheet('wwt_cornstover')
F.set_flowsheet(flowsheet)
cornstover_sys = create_cs_system(include_blowdown_recycle=True)

u = F.unit
wwt_units = [i for i in u if i.ID[1:3]=='60']
OSBL_units = (*wwt_units, u.CWP, u.CT, u.PWC, u.ADP,
              u.T701, u.T702, u.P701, u.P702, u.M701, u.FT,
              u.CSL_storage, u.DAP_storage, u.BT)
cornstover_tea = cs.create_tea(cornstover_sys, OSBL_units, [u.U101])
ethanol = F.stream.ethanol

# Compare MESP
assert(cornstover_tea.IRR==cs.cornstover_tea.IRR==0.1)
print(f'\n\nIRR = {cornstover_tea.IRR:.0%}')
MESP_old = get_MESP(cs.ethanol, cs.cornstover_tea, 'old cs sys')
MESP_new = get_MESP(ethanol, cornstover_tea, 'new cs sys')

# %%

# =============================================================================
# Util functions for result comparison
# =============================================================================

# Old system
cs_wwt_units = [i for i in cs.cornstover_sys.units if i.ID[1:3]=='60']
old_capex = cs.WWTC.installed_cost / 1e6
old_capex_ratio = old_capex/(cs.cornstover_tea.installed_equipment_cost/1e6)

old_power_wwt = cs.WWTC.power_utility.rate
old_power_tot = sum(i.power_utility.consumption for i in cs.cornstover_sys.units)
old_power_ratio = old_power_wwt / old_power_tot

old_power_net = sum(i.power_utility.rate for i in cs.cornstover_sys.units)

# New system
new_capexes = {i.ID: i.installed_cost/1e6 for i in wwt_units}
new_capex = sum(i for i in new_capexes.values())
new_capex_ratio = new_capex/(cornstover_tea.installed_equipment_cost/1e6)

new_powers_wwt = {i.ID: i.power_utility.rate/1e3 for i in wwt_units}
new_power_wwt = sum(i for i in new_powers_wwt.values())
new_power_tot = sum(i.power_utility.consumption for i in cornstover_sys.units)/1e3
new_power_ratio = new_power_wwt / new_power_tot

new_power_net = sum(i.power_utility.rate for i in cornstover_sys.units)/1e3

s = F.stream
# Hf in kJ/hr
net_e = s.ethanol.Hf/3600/1e3 + u.BT.power_utility.rate/1e3
net_e_ratio = net_e/(s.cornstover.Hf/3600/1e3)

# Water
# water_usage = (u.PWC.F_mass_in+s.cornstover.imass['Water'])/s.ethanol.F_mass # 18 kg/kg
water_usage = u.PWC.F_mass_in/s.ethanol.F_mass # 17 kg/kg
# water_consumption = (u.PWC.ins[1].F_mass-u.PWC.outs[1].F_mass+s.cornstover.imass['Water']) / \
#     s.ethanol.F_mass # about 1.7 kg/kg
water_consumption = (u.PWC.ins[1].F_mass-u.PWC.outs[1].F_mass) / \
    s.ethanol.F_mass # about 0.8 kg/kg

# Wastewater
from utils import compute_stream_COD
wastewater = u.M601.F_mass_in/s.ethanol.F_mass # about 18 kg/kg
COD = compute_stream_COD(u.M601.outs[0]) # about 54 g COD/L

# OLR
from utils import auom
_ft_to_m3 = auom('ft3').conversion_factor('m3')
old_OLR_R601 = compute_stream_COD(cs.R601.ins[0])*cs.R601.ins[0].F_vol / \
    (4*31*1e6*auom('gal').conversion_factor('m3')) * 24 # 1.4 g COD/L/d
old_OLR_R602 = compute_stream_COD(cs.R602.ins[0])*cs.R602.ins[0].F_vol / \
    (3*25*115*344*_ft_to_m3) * 24 # 0.7 g COD/L/d

new_OLR_R601 = compute_stream_COD(u.R601.ins[0])*u.R601.ins[0].F_vol / \
    (u.R601.Vliq) * 24 # 30 g COD/L/d
V_R602 = u.R602.D_tank*u.R602.W_tank*u.R602.L_CSTR*u.R602.N_train * \
    _ft_to_m3
new_OLR_R602 = compute_stream_COD(u.R602.ins[0])*u.R602.ins[0].F_vol / \
    V_R602 * 24 # 10.3 g COD/L/d
# new_OLR_R603 = compute_stream_COD(u.R603._inf)*u.R603._inf.F_vol / \
#     (u.R603.design_results['Volume [ft3]']*_ft_to_m3) * 24 # 2.25 g COD/L/d
new_OLR_R603 = u.R603.OLR # 2.25 g COD/L/d

# Adjust methane production
def adjust_methane():
    from utils import get_digestable_chemicals
    flowsheet_ch4 = bst.Flowsheet('wwt_cornstover_ch4')
    F.set_flowsheet(flowsheet_ch4)
    cornstover_sys_ch4 = create_cs_system(include_blowdown_recycle=True,
                                          skip_R603=True)
    u_ch4 = F.unit
    wwt_units = [i for i in u if i.ID[1:3]=='60']
    OSBL_units = (*wwt_units, u_ch4.CWP, u_ch4.CT, u_ch4.PWC, u_ch4.ADP,
                  u_ch4.T701, u_ch4.T702, u_ch4.P701, u_ch4.P702, u_ch4.M701, u_ch4.FT,
                  u_ch4.CSL_storage, u_ch4.DAP_storage, u_ch4.BT)

    cornstover_tea_ch4 = cs.create_tea(cornstover_sys_ch4, OSBL_units, [u_ch4.U101])

    BD_dct = {k.ID: 1. for k in get_digestable_chemicals(chems)}
    u_ch4.R601.biodegradability = BD_dct
    u_ch4.R601._refresh_rxns(X_biogas=0.86, X_growth=0.05)
    # About 5481, vs. 5681 from Humbird, about 3-4% less,
    # might be due to the different CH4/CO2 ratios in the biogas production reaction,
    # Humbird assumed 51%:49% (1.04) CH4:CO2 on a molar basis, here is about 1
    # print(u.R601.outs[0].imass['CH4'])
    return flowsheet_ch4, cornstover_sys_ch4, cornstover_tea_ch4

flowsheet_ch4, cornstover_sys_ch4, cornstover_tea_ch4 = adjust_methane()

get_MESP(F.stream.ethanol, cornstover_tea_ch4, 'new cs sys with higher BD')

# %%

get_ratio = lambda cornstover, ethanol: \
    ethanol.F_mass/cs.ethanol_density_kggal/(cornstover.F_mass-cornstover.imass['Water'])

lca_streams_cs = [
    cs.denaturant,
    cs.cellulase,
    cs.sulfuric_acid,
    cs.DAP,
    cs.CSL,
    cs.ammonia,
    cs.FGD_lime,
    cs.caustic,
    cs.emissions,
    ]

# One stream that representing all chemicals
lca_stream_cs = bst.Stream('lca_stream_cs')
lca_stream_cs.mix_from(lca_streams_cs)

GWP_cs = get_cs_GWP(lca_stream_cs, cs.flowsheet,
                    get_ratio(cs.cornstover, cs.ethanol))

# Get the gross results
print(f'Total GWP for original cs sys is {GWP_cs:.2f} kg CO2-eq/gal ethanol.')

s_ch4 = flowsheet_ch4.stream
lca_streams_ch4 = [
    s_ch4.denaturant,
    s_ch4.cellulase,
    s_ch4.sulfuric_acid,
    s_ch4.DAP,
    s_ch4.CSL,
    s_ch4.ammonia,
    s_ch4.FGD_lime,
    s_ch4.emissions,
    ]

# One stream that representing all chemicals
lca_stream_ch4 = bst.Stream('lca_stream_ch4')
lca_stream_ch4.mix_from(lca_streams_ch4)

GWP_ch4 = get_cs_GWP(lca_stream_ch4, flowsheet_ch4,
                    get_ratio(s_ch4.cornstover, s_ch4.ethanol))

# Get the gross results
print(f'Total GWP for new cs sys with higher BD is {GWP_ch4:.3f} kg CO2-eq/gal ethanol.')

# %%

# # C/N ratio
# from _utils import get_CN_ratio
# R601_CN = get_CN_ratio(u.R601._inf)


import os

print("Kindly put this file in the folder where you have lastsave.txt/the file which has all the operations")

print("Press 1 if your filename is lastsave.txt. Else press any other key")
n = input()

if(n=='1'):
    fname = "lastsave.txt"
else:
    print("Enter your filename")
    fname = input()
    if('.txt' not in fname):
        fname = fname+ '.txt'

f= open(fname, "r")
opfile = 'Youroutput.txt'
fw = open(opfile, "w+")

Lines = f.readlines()
for x in Lines:
    if('>' in x):
        x = x[2:]
        fw.write(x)
fw.close()

print("Do you want to change the extension from .txt to .r? Press 1 for Yes.")
n = input()
if n=='1':
    base = os.path.splitext(opfile)[0]
    os.rename(opfile, base + '.r')


from functools import reduce

def product(numbers):
    result = []
    for i in numbers:
        result.append(reduce((lambda x, y: x*y),
                             [j for j in numbers if j != i]))
    return result

print(product([1, 7, 3, 4]))


# -*- coding:utf-8 -*-
# @Time: 2020/8/3 9:58
# @Author: duiya duiyady@163.com

"""
给定两个字符串形式的非负整数 num1 和num2 ，计算它们的和。

注意：
num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库， 也不能直接将输入的字符串转换为整数形式。
"""

def addStrings(num1, num2):
    if len(num1) < len(num2):
        num1, num2 = num2, num1
    result = [0]*(len(num1)+1)
    jia = 0
    for i in range(1, len(num2)+1):
        tmp = int(num2[-i]) + int(num1[-i]) + jia
        result[-i] = str(tmp%10)
        jia = tmp//10
    for i in range(len(num2)+1, len(num1)+1):
        tmp = int(num1[-i]) + jia
        result[-i] = str(tmp % 10)
        jia = tmp // 10
    if jia !=0:
        result[0] = str(jia)
    else:
        result.pop(0)
    return "".join(result)

if __name__ == '__main__':
    print(addStrings("123", "345"))


def main():
    n = int(input())
    A = list(map(int, input().split()))
    assert len(A) == n

    coins = 0
    sign = 1 # 1 -- plus, 0 -- minus
    sign_defined = False
    for elm in A:
        if elm > 1:
            coins += elm - 1
        elif elm <= -1:
            coins += -1 - elm
            sign = 1 - sign
        elif elm == 0:
            coins += 1
            sign_defined = True

    if sign_defined == False and sign == 0:
        coins += 2

    print(coins)

    pass

import sys
input = sys.stdin.readline
if __name__ == "__main__":
    main()


from flask import Flask
from flask import jsonify
from flask import request
from applicationinsights.flask.ext import AppInsights
from healthcheck import HealthCheck, EnvironmentDump

app_name = 'comentarios'
app = Flask(app_name)
app.debug = True

# Azure Application Insights
app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = '__APPINSIGHTS_INSTRUMENTATIONKEY__'
appinsights = AppInsights(app)

@app.after_request
def after_request(response):
    appinsights.flush()
    return response

# Health Check
health = HealthCheck()
envdump = EnvironmentDump()

def api_available():
    return True, "api ok"

health.add_check(api_available)

def application_data():
    return {"health check": "ok"}

envdump.add_section("application", application_data)

app.add_url_rule("/healthcheck", "healthcheck", view_func=lambda: health.run())
app.add_url_rule("/environment", "environment", view_func=lambda: envdump.run())

comments = {}

@app.route('/api/comment/new', methods=['POST'])
def api_comment_new():
    request_data = request.get_json()

    email = request_data['email']
    comment = request_data['comment']
    content_id = '{}'.format(request_data['content_id'])

    new_comment = {
            'email': email,
            'comment': comment,
            }

    if content_id in comments:
        comments[content_id].append(new_comment)
    else:
        comments[content_id] = [new_comment]

    message = 'comment created and associated with content_id {}'.format(content_id)
    response = {
            'status': 'SUCCESS',
            'message': message,
            }
    return jsonify(response)

@app.route('/api/comment/list/<content_id>')
def api_comment_list(content_id):
    content_id = '{}'.format(content_id)

    if content_id in comments:
        return jsonify(comments[content_id])
    else:
        message = 'content_id {} not found'.format(content_id)
        response = {
                'status': 'NOT-FOUND',
                'message': message,
                }
        return jsonify(response), 404


from pathlib import Path
from boofuzz import *

# vulnserver
ip = "127.0.0.1"
port = 9999

# vulnserver Connection
connection = SocketConnection(ip, port, proto="tcp")
target = Target(connection=connection)
session = Session(target=target)

# Fuzzing Setup
s_initialize("vulnserver-trun")

s_string("LTER", fuzzable=False)
s_delim(" ", fuzzable=False)
s_string("something")       # Fuzzing Point

session.connect(s_get("vulnserver-trun"))

session.fuzz()

vulnserver/LTER - SEH Overwrite/fuzz_lter.py


import os

train_task_id = '3T736'    # train任务id
initial_epoch = 0          # 起始epoch
epoch_num = 24             # 总共训练epoch数
lr = 1e-3                  # 学习率
decay = 5e-4               # 学习率衰减率
# clipvalue = 0.5  # default 0.5, 0 means no clip

patience = 5
load_weights = False                   # 是否加载权值
lambda_inside_score_loss = 4.0         # 几个loss的lambda，内部得分loss
lambda_side_vertex_code_loss = 1.0     # 几个loss的lambda，边界得分loss
lambda_side_vertex_coord_loss = 1.0    # 几个loss的lambda，角点得分loss

total_img = 10000                                            # 图片总数
validation_split_ratio = 0.1                                 # 验证图片比例
max_train_img_size = int(train_task_id[-3:])                 # 训练图像的尺寸为train id的后三位数
max_predict_img_size = int(train_task_id[-3:])  # 2400       # 最大的预测图像尺寸为train id的后三位数

# 与其让它在运行最崩溃，不如在出现错误条件时就崩溃，这时候就需要assert断言的帮助
# assert 表达式, 参数
# if not 表达式: 参数
assert max_train_img_size in [256, 384, 512, 640, 736], \
    'max_train_img_size must in [256, 384, 512, 640, 736]'

# 为不同尺寸的训练图像指定不同的batch_size
if max_train_img_size == 256:
    batch_size = 8
elif max_train_img_size == 384:
    batch_size = 4
elif max_train_img_size == 512:
    batch_size = 2
else:
    batch_size = 1

# 每一个epoch的迭代总次数等于训练图片除以batch的大小，双线除号表示取整
steps_per_epoch = total_img * (1 - validation_split_ratio) // batch_size
validation_steps = total_img * validation_split_ratio // batch_size

data_dir = 'icpr/'                                                 # 数据文件夹
origin_image_dir_name = 'image_10000/'                             # 原始image文件夹
origin_txt_dir_name = 'txt_10000/'                                 # 原始gt文件夹
train_image_dir_name = 'images_%s/' % train_task_id                # 训练任务的image文件夹
train_label_dir_name = 'labels_%s/' % train_task_id                # 训练任务的label文件夹
show_gt_image_dir_name = 'show_gt_images_%s/' % train_task_id      # 展示gt图片的文件夹
show_act_image_dir_name = 'show_act_images_%s/' % train_task_id    # 展示act图片的文件夹
gen_origin_img = True                                              # 是否产生原始图像
draw_gt_quad = True                                                # 是否绘制gt
draw_act_quad = True                                               # 是否绘制act
val_fname = 'val_%s.txt' % train_task_id                           # 保存验证数据gt信息的文本
train_fname = 'train_%s.txt' % train_task_id                       # 保存训练数据gt信息的文本
# in paper it's 0.3, maybe to large to this problem
shrink_ratio = 0.2                                                 # 文本框的收缩比率
# pixels between 0.2 and 0.6 are side pixels
shrink_side_ratio = 0.6                                            # 左右边框的收缩比率
epsilon = 1e-4

num_channels = 3                                                   # 图像通道数
feature_layers_range = range(5, 1, -1)                             # 特征层的范围 [5、4、3、2]
# feature_layers_range = range(3, 0, -1)
feature_layers_num = len(feature_layers_range)                     # 特征层的数量
# pixel_size = 4
pixel_size = 2 ** feature_layers_range[-1]                         # 像素尺寸等于2的feature_layers_range的最后一个元素次方，即2**2 = 4
print(pixel_size)
locked_layers = False

# 创建保存模型的文件夹
if not os.path.exists('model'):
    os.mkdir('model')
if not os.path.exists('saved_model'):
    os.mkdir('saved_model')

# 训练过程的模型保存路径
model_weights_path = 'model/weights_%s.{epoch:03d}-{val_loss:.3f}.h5' \
                     % train_task_id
# 最终模型文件及权值的保存位置
saved_model_file_path = 'saved_model/east_model_%s.h5' % train_task_id
saved_model_weights_file_path = 'saved_model/east_model_weights_%s.h5'\
                                % train_task_id

pixel_threshold = 0.9                       # 像素的阈值？
side_vertex_pixel_threshold = 0.9           # 边界顶点像素阈值？
trunc_threshold = 0.1                       # 截断阈值？
predict_cut_text_line = False               # 是否预测被切割的文本行？
predict_write2txt = True                    # 是否将结果保存为txt


import os
import sys

from bisect import bisect_left, bisect_right

def solve(shots, players):
    s_array, e_array = [], []
    for s in shots:
        i, j = s
        s_array.append(i)
        e_array.append(j)
    s_array.sort()
    e_array.sort()
    result = 0
    for p in players:
        i, j = p
        result += bisect_right(s_array, j) - bisect_left(e_array, i)
    return result

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nm = input().split()

    n = int(nm[0])

    m = int(nm[1])

    shots = []

    for _ in range(n):
        shots.append(list(map(int, input().rstrip().split())))

    players = []

    for _ in range(m):
        players.append(list(map(int, input().rstrip().split())))

    result = solve(shots, players)

    fptr.write(str(result) + '\n')

    fptr.close()


from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from main.models import mquiz

class StartQuizForm(forms.Form):

    how_many_questions = forms.IntegerField(help_text="How many questions do you want (default=5) ?")

    def clean_renewal_date(self):
        data = self.cleaned_data['how_many_questions']

        # Check if a date is not in the past.
        if data < 0:
            raise ValidationError(_('Invalid number. Enter a number more than 0'))

        # Check if a date is in the allowed range (+4 weeks from today).
        if data > 10 :
            raise ValidationError(_('Invalid number. Enter a number greater than 10'))

        # Remember to always return the cleaned data.
        return data

class QuestionForm(forms.Form):
    def __init__(self,selection):
       self.selection = selection
       self.options = forms.ChoiceField(choices=selection,widget=forms.RadioSelect)

class CreateQuizForm(forms.ModelForm):

   def __init__(self, *args, **kwargs):
       super(forms.ModelForm, self).__init__(*args, **kwargs)
       # This is a way to override the labels on the html. Default is the
       # column name itself. But wee need it descriptive.
       self.fields['qdesc'].label = 'Question description'
       self.fields['qop1'].label = 'Option 1'
       self.fields['qop2'].label = 'Option 2'
       self.fields['qop3'].label = 'Option 3'
       self.fields['qop4'].label = 'Option 4'
       self.fields['qop5'].label = 'Option 5'
       self.fields['qans'].label = 'Correct option'
       self.fields['qhint'].label = 'Hint'
       self.fields['qsol'].label = 'Solution description'
       self.fields['qimage'].label = 'Select Image to Upload'
       self.fields['qhimg'].label = 'Select Image to Upload'
       self.fields['qsimg'].label = 'Select Image to Upload'

   class Meta(object):
      model = mquiz
      fields = ['qdesc','qop1','qop2','qop3','qop4','qop5',
                'qans','qhint','qsol','qimage','qhimg','qsimg']
      widgets = {
       'qdesc' : forms.Textarea(attrs={'class': 'form-control', 'rows':'5'} ),
       'qop1'  : forms.Textarea(attrs={'class': 'form-control', 'rows':'3'} ),
       'qop2'  : forms.Textarea(attrs={'class': 'form-control', 'rows':'3'} ),
       'qop3'  : forms.Textarea(attrs={'class': 'form-control', 'rows':'3'} ),
       'qop4'  : forms.Textarea(attrs={'class': 'form-control', 'rows':'3'} ),
       'qop5'  : forms.Textarea(attrs={'class': 'form-control', 'rows':'3'} ),
       'qhint' : forms.Textarea(attrs={'class': 'form-control', 'rows':'3'} ),
       'qsol'  : forms.Textarea(attrs={'class': 'form-control', 'rows':'3'} ),
       'qimage': forms.ClearableFileInput(),
       'qhimg': forms.ClearableFileInput(),
       'qsimg': forms.ClearableFileInput(),

      }


import tkinter as tk
from Python.TomasArduino import *
from Python.Writer import *

writer = Writer(name = "log1")
arduino = TomasArduino(port = "COM6", want_threading = True, writer = writer)

def onKeyPress(event):
    key = ord(event.char);
    if key == 32:  # space
        arduino.connect()
        if(arduino.is_open()): text.insert('end', "Connected")
        else: text.insert('end', "Not connected")
    if key == 27:  # ESC
        text.insert('end', "Disconnecting")
        arduino.disconnect()
    if key == 13:  # Enter
        text.insert('end', "Blinking")
        arduino.blink()

def onKeyRelease(event):
    key = ord(event.char);
    if key == 107: #k
        text.delete(1.0, 'end')

# Graphical window initialisation
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.bind('<KeyRelease>', onKeyRelease)
text.insert('end', 'Press enter to blink. Escape to disconnect. Space to connect')

def updating_sensors():
    arduino.check_sensors()
    root.after(10, updating_sensors)

root.after(10, updating_sensors)
root.mainloop()


from groupyou.jobs.reaction import Reaction
import urllib.request
import http.client as htcli

class Weather(Reaction):

    def __init__(self):
        self.message = ''

    def react(self, user_name, text, attachments):
        if text.startswith('weather'):
            command = text.split(' ')
            if len(command) == 3:
                if command[1] == 'forecast':
                    pass
            elif len(command) == 2:
                if command[1]:
                    try:
                        float(command[1])
                        if len(command[1]) is 5:
                            self.message = self.get_current_zip(zipcode=command[1])
                            return True
                    except ValueError:
                        self.message = 'Bad zipcode'
                        return True

            else:
                self.message = 'Bad format for weather call'
                return True

            return True
        return False

    def get_current_zip(self, zipcode="00000"):
        conn = htcli.HTTPConnection('http://api.wunderground.com')
        conn.request('GET', '/api/420931bcbb94c902/conditions/q/' + zipcode + '.json')
        response = conn.getresponse().read()

        # request = urllib.request.urlopen('http://api.wunderground.com/api/420931bcbb94c902/conditions/q/' + zipcode + '.json')
        # result = request.read()
        # request.close()
        print(response)
        self.message = 'not good'
        return 'not good'

    def run(self, chat):
        chat.add_text(self.message)
        chat.flush()
        return


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 24 10:20:47 2017

@author: nekar01
"""

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

#Need to understand more about the pNandas
#Data Visualization is a great skill
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,1].values

from sklearn.cross_validation import train_test_split
Xtrain,Xtest,ytrain,ytest = train_test_split(X,y,test_size=1/3,random_state = 0)

from sklearn.linear_model import LinearRegression
regressor = LinearRegression();
#trainig the regressor
regressor.fit(Xtrain,ytrain)

ypred = regressor.predict(Xtest)

# Visualizing the training set
plt.scatter(Xtrain,ytrain,color="red")
plt.plot(Xtrain,regressor.predict(Xtrain),color ="blue")
plt.title('Graph for Training Site')
plt.xlabel('Experience_training Set')
plt.ylabel('Salary_trainig Set')
plt.show()

# Visualizing the test set
plt.scatter(Xtest,ytest,color="red")
plt.plot(Xtrain,regressor.predict(Xtrain),color ="blue")
plt.title('Graph for Training Site')
plt.xlabel('Experience_training Set')
plt.ylabel('Salary_trainig Set')
plt.show()


"""
pghoard - inotify wrapper

Copyright (c) 2015 Ohmu Ltd
See LICENSE for details
"""

from ctypes import c_int, c_uint32, c_char_p
from threading import Thread
import ctypes
import errno
import logging
import os
import select
import struct

class InotifyEvent(ctypes.Structure):
    _fields_ = [('wd', c_int),
                ('mask', c_uint32),
                ('cookie', c_uint32),
                ('len', c_uint32),
                ('name', c_char_p)]

s_size = 16
# default 2048 events
INOTIFY_EVENT_BUFFER_SIZE = 2048 * (ctypes.sizeof(InotifyEvent) + s_size)

event_types = {
    "IN_MODIFY": 0x00000002,
    "IN_CREATE": 0x00000100,
    "IN_MOVED_FROM": 0x00000040,
    "IN_MOVED_TO": 0x00000080,
    "IN_DELETE": 0x00000200,
    "IN_DELETE_SELF": 0x00000400,
    "IN_IGNORED": 0x8000
}

IN_NONBLOCK = 0x00004000

def parse_inotify_buffer(event_buffer):
    i = 0
    while i + s_size <= len(event_buffer):
        wd, mask, cookie, length = struct.unpack_from('iIII', event_buffer, i)
        name = event_buffer[i + s_size:i + s_size + length].rstrip(b'\0')
        i += s_size + length
        yield wd, mask, cookie, name

class InotifyWatcher(Thread):
    def __init__(self, compression_queue, ignore_modified=True):
        Thread.__init__(self)
        # use the newer form for future-proofness
        self.log = logging.getLogger("PGHoardInotify")
        self.ignore_modified = ignore_modified
        self.libc = ctypes.CDLL("libc.so.6")
        self.fd = self.libc.inotify_init()
        self.watch_to_path = {}
        self.cookies = {}
        self.running = True
        self.compression_queue = compression_queue
        self.timeout = 1.0
        self.log.debug("InotifyWatcher initialized")

    def add_watch(self, path):
        mask = 0
        for v in event_types.values():
            mask |= v
        watch = self.libc.inotify_add_watch(self.fd, c_char_p(path.encode("utf8")), c_uint32(mask))
        if watch < 0:
            return
        self.watch_to_path[watch] = path
        self.log.debug("Added watch for path: %r", path)

    def read_events(self):
        event_buffer = None
        while self.running:
            try:
                rlist, _, _ = select.select([self.fd], [], [], self.timeout)
                if rlist:
                    for fd in rlist:
                        event_buffer = os.read(fd, INOTIFY_EVENT_BUFFER_SIZE)
            except OSError as e:
                if e.errno == errno.EINTR:
                    continue
            break
        if not event_buffer:
            return
        for wd, mask, cookie, name in parse_inotify_buffer(event_buffer):
            if wd == -1:
                continue
            self.create_event(wd, mask, cookie, name)

    def create_event(self, wd, mask, cookie, name):
        if mask & event_types['IN_IGNORED']:
            # explicit removal of watch or dir, ignore
            return
        full_path = os.path.join(self.watch_to_path[wd], name.decode("utf8"))
        if mask & event_types["IN_CREATE"] > 0:
            self.compression_queue.put({"type": "CREATE", "full_path": full_path})
        elif not self.ignore_modified and mask & event_types["IN_MODIFY"] > 0:  # no need for these
            self.compression_queue.put({"type": "MODIFY", "full_path": full_path})
        elif mask & event_types["IN_DELETE"] > 0:
            self.compression_queue.put({"type": "DELETE", "full_path": full_path})
        elif mask & event_types["IN_DELETE_SELF"] > 0:
            directory = self.watch_to_path.pop(wd, "")
            self.log.debug("Directory: %r that we were watching has been deleted, removing watch",
                           directory)
            self.libc.inotify_rm_watch(self.fd, wd)
        elif mask & event_types["IN_MOVED_FROM"] > 0:
            self.cookies[cookie] = full_path
        elif mask & event_types["IN_MOVED_TO"] > 0:
            src_path = self.cookies.pop(cookie, None)
            if src_path:
                self.compression_queue.put({"type": "MOVE", "full_path": full_path, "src_path": src_path})
            else:
                self.compression_queue.put({"type": "CREATE", "full_path": full_path})

    def run(self):
        self.log.debug("Starting InotifyWatcher")
        while self.running:
            self.read_events()
        self.log.info("Quitting InotifyWatcher")
        os.close(self.fd)


import torch
import torch.nn as nn
import torch.nn.functional as F

class DQN(nn.Module):
    def __init__(self, input_size=192):
        super(DQN, self).__init__()

        self.fc1 = nn.Linear(input_size, 1024)
        self.fc2 = nn.Linear(1024, 512)
        self.fc3 = nn.Linear(512, 256)
        self.fc4 = nn.Linear(256, 128)
        self.fc5 = nn.Linear(128, 4)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = F.relu(self.fc4(x))
        x = self.fc5(x)

        return x


from .base_chart import BaseChart
from collections import defaultdict

class PercentageAreaChart(BaseChart):

    def __init__(self):
        super().__init__()
        self.__type__ = 'percentage_area'
        # self.__description__ = 'percentage_area chart'
        self.__xAxis__ = []
        self.__yAxis__ = {
            "title": "Total percent market share"
        }
        self.__series__ = []

    def _available_types(self):
        self.available_types = ['percentage_area']

    def transformation(self, raw_data):
        self._set_common_properties(raw_data)

        # print(raw_data)
        str = raw_data.get('data')
        groupResult = str.groupby('X2').groups
        result = []
        xAxis = []
        flag = True

        for key,value in groupResult.items():
            name = key
            d = []

            if name == 'PLAN ATTRIBUTION COMPONENT':
                continue

            for i in value.values:
                column = str.loc[i]

                d.append(float(column['Y1']))
                if flag:
                    xAxis.append(column['X1'])

            result.append({'name':key,'data':d})

            flag = False

        # title = {'text':raw_data.get('F00062_all_0_S2AC').get('title')}
        self.__xAxis__ = xAxis
        self.__series__ = result
        # self._get_hover_data(xAxis)
        self._get_hover_data(xAxis, raw_data)
        # allResult = {
        #     'title': title,
        #     'series':result,
        #     'categories': x
        # }

    def _get_hover_data(self, xAxis, raw_data):

        if raw_data.get('df_highlights')[0] != True:
            return

        df_highlights = raw_data.get('df_highlights')[1]
        narrative_highlights = raw_data.get('narrative_highlights')[1]

        highlight = []
        hover_data_list = []

        for i in range(len(df_highlights)):

            # print(df_highlights[i], "---", narrative_highlights[i])

            if df_highlights[i].find(narrative_highlights[i]) == -1:
                continue;

            index = xAxis.index(narrative_highlights[i])
            hover_data_list.append({"group":0, "index":index})

            highlight.append({"hoverData":hover_data_list, "hoverContent":narrative_highlights[i]})
            break;

        self.__highlight__ = highlight


from fuzzysearch import find_near_matches

def find_delimiter(delimiter, text, max_l_dist=0.3):
    """
    Match <delimiter> in <text> with <max_l_dist>*len(<delimiter>) authorized primary operations
    (ids).
    Note: delimiter and text should be lower case.
    :param delimiter: str. Ex: "be it known"
    :param text: str.
    :param max_l_dist: float
    :return: fuzzysearch.common.Match
    """
    assert (max_l_dist >= 0) & (max_l_dist <= 1)
    max_l_dist_delimiter = int(len(delimiter) * max_l_dist)
    match = find_near_matches(delimiter, text, max_l_dist=max_l_dist_delimiter)

    return match


import json
import boto3

def lambda_handler(event, context):

    client = boto3.client('s3')

     # copy placeholder css to css dir
    response = client.copy_object(
        ACL="public-read",
        Bucket="csufprojectwebfiles",
        CopySource={'Bucket': 'csufprojectclients', 'Key': 'starterFolder/css/'+ event['style'] +'/stylesheet.css'},
        Key= event['subdomain'] + "/" + "css/stylesheet.css"
    )

    return "OK";


import torch
import pandas as pd
import numpy as np

from torch.utils import data

class FaceDataset(data.Dataset):
    'Characterizes a dataset for PyTorch'
    def __init__(self, folder_name, training = True, transform = None):
        'Initialization'
        self.transform = transform

        if training:
            face_data = np.array(pd.read_csv(folder_name+"/train_face.csv", index_col=None, header=None))
            nface_data = np.array(pd.read_csv(folder_name+"/train_nface.csv", index_col=None, header=None))
        else:
            face_data = np.array(pd.read_csv(folder_name+"/test_face.csv", index_col=None, header=None))
            nface_data = np.array(pd.read_csv(folder_name+"/test_nface.csv", index_col=None, header=None))

        face_label = np.ones(len(face_data), dtype=int)
        nface_label = np.zeros(len(nface_data), dtype=int)

        self.data = np.concatenate([face_data, nface_data], axis=0)
        self.label = np.concatenate([face_label, nface_label], axis=0)

        #divide by 255
        self.data = self.data / 255.0

        #reshape
        self.data = self.data.reshape(-1, 16, 16).astype(np.float32)

        shuffle_index = np.arange(len(self.data))
        np.random.shuffle(shuffle_index)

        self.data = self.data[shuffle_index]
        self.label = self.label[shuffle_index]

        return

    def __len__(self):
        'Denotes the total number of samples'
        return len(self.data)

    def __getitem__(self, index):
        'Generates one sample of data'
        # Load data and get label
        X = self.data[index]
        y = self.label[index]

        if self.transform is not None:
            X = self.transform(X)

        return X, y


from turtle import Turtle
import random
import time
colors = ["yellow", "green", "red", "purple", "pink", "blue"]

class Obstacle():
    def __init__(self):
        self.segments = []
        self.xcor = 290
        self.speed = 3

    def create_obstacle(self):
        new_obstacle = Turtle()
        new_obstacle.color(random.choice(colors))
        new_obstacle.penup()
        new_obstacle.shape("square")
        new_obstacle.shapesize(stretch_wid=0.5, stretch_len=random.randrange(1, 3))
        new_ycor = random.randrange(-250, 270)
        new_obstacle.goto(self.xcor, new_ycor)
        self.segments.append(new_obstacle)
        self.xcor += random.randint(20, 50)

    def move(self):
        for segment in self.segments:
            segment.goto(segment.xcor() - self.speed, segment.ycor())

    def move_faster(self):
        self.speed += 1

    def reset_speed(self):
        self.speed = 3


"""
This program uses webcrawling to give you most needed information along with
some of the knowledge that you might also need to know alongside of the one
you searched for.
Hopefully will add machine learning part of the code for more accurate results
And also sort the results in SQL databases using django***

"""

from bs4 import BeautifulSoup as bs
import requests
import nltk
import sys
import re
from urllib.parse import urljoin, urlparse
import time
from os.path import exists
import argparse

print(sys.executable)
print(sys.version)

class Crawler:
    def __init__(self, container, handler):
        self.container = container
        self.handler = handler
        if(exists(self.handler)):
            file = open(self.handler, 'a')
            self.file = file
        else:
            file = open(self.handler, 'w')
            self.file = file
            self.file.write("Word,Tense,Link\n")

    def checkLegit(self, ptags):
        for pIter, p in enumerate(ptags):
            if(p.text != "\n"):
                aIter = 0
                atags = ptags[pIter].find_all("a", recursive=False)
                # if below throws an IndexError it means that it wasn't able to
                # find any atags in the current p tag
                try:
                    href = atags[aIter]['href']
                except IndexError:
                    print("Wasn't able to find any href links. Skipping loop.\n")
                    continue
                while('/wiki/Help:' in href):
                    aIter += 1
                    href = atags[aIter]['href']
                return href

    def getLinks(self):
        try:
            url = requests.get(self.container[-1])
        except Exception:
            print("Could not receive GET request from the website.")
            print("Re-check html container array")
            sys.exit(0)
        html = url.text
        soup = bs(html, 'html.parser')
        div = soup.find(id="mw-content-text").find(class_="mw-parser-output")
        ptags = div.find_all("p", recursive=False)
        # print("Run checkLegit()")
        href = self.checkLegit(ptags)
        next_url = urljoin("https://en.wikipedia.org", href)
        # TODO: could have all the href links on the site in a list
        # and iter through THAT and get next_url, like a tree structure
        self.container.append(next_url)

    def partOfSpeech(self, tagged, word_list):
        for element in tagged:
            word, tense = element
            if(tense in ['NOUN', 'VERB', 'NUM', 'ADJ']):
                word_list.append(element)

    def categorize(self, urlpath, word_list, file):
        for words in sorted(word_list, key=lambda word: word[1]):
            for char in ['\'', '(', ')', ' ']:
                if(char in words):
                    words = words.replace(char, "")

            word, tense = words
            file.write("{},{},{} \n".format(word, tense, urlpath))

    def wordCrawl(self):
        print(self.container)
        # file = open(self.handler, 'w')
        word_list = list()
        for link in self.container:
            try:
                url = requests.get(link)
            except Exception:
                print("ConnectionError: Get request denied.\n Request Overflow")
                print("Shutting off...")
                exit(1)
            html = url.text
            soup = bs(html, 'html.parser')
            ptags = soup.find(id="mw-content-text").find_all("p")
            # print(ptags)
            for ptag in ptags:
                if(ptag == "\n"):
                    print("Skipping \n's")
                    pass
                else:
                    tag = ptag.get_text()  # all the text from one <p>
            words = re.sub('[^A-Za-z0-9]+', ' ', tag)
            token = nltk.word_tokenize(words)
            tagged = nltk.pos_tag(token, tagset='universal')
            self.partOfSpeech(tagged, word_list)

            # to append url link that leads to the word and tense information
            urlpath = urlparse(link).path

            self.categorize(urlpath, word_list, self.file)
        self.file.close()

# TODO: Implement a way to read wikipedia sites with .m url (https://en.m.wikipedia.org/wiki/Centralisation)

if __name__ == '__main__':
    default_count = 5
    iter_count = 0
    param_count=sys.argv[1]
    param_link=sys.argv[2]
    container = []  # container for keeping track of urls
    # handler = "dictionary.csv"  # file for keeping track of words and its data
    if(param_count != None):
        param_count = default_count
    file_link = "DataFile/data.csv"
    container.append(param_link)
    crawler1 = Crawler(container, handler=file_link)
    ctime1 = time.time()
    while(iter_count < param_count):
        crawler1.getLinks()
        time.sleep(2)  # halt crawling(Robot.txt)
        iter_count += 1
    ctime2 = time.time()
    print("How long it took to crawl: {} (s)".format(ctime2-ctime1))
    print("container", crawler1.container)
    wtime1 = time.time()
    crawler1.wordCrawl()
    wtime2 = time.time()
    print("How long it took to create csv file: {} (s)".format(wtime2-wtime1))

    arg_help = argparse.ArgumentParser(description='\b[Wikipedia Crawler]')
    arg_help.add_argument('integers', metavar='N', type=int, nargs='+', help='Number of crawls \n default is 5')
    arg_help.add_argument('link', metavar='href link', type=str, nargs=1, help='Link to wikipedia topic you want to crawl')


import sys
import subprocess

from bincrafters.build_shared import printer, get_os
import bincrafters.build_template_default as build_template_default
import bincrafters.build_template_header_only as build_template_header_only
import bincrafters.build_template_installer as build_template_installer
from bincrafters.autodetect import *

def _flush_output():
    sys.stderr.flush()
    sys.stdout.flush()

def run_autodetect():
    has_custom_build_py, custom_build_py_path = is_custom_build_py_existing()

    if has_custom_build_py:
        printer.print_message("Custom build.py detected. Executing ...")
        _flush_output()
        subprocess.run(["python",  "{}".format(custom_build_py_path)], check=True)
        return

    recipe_is_installer = is_installer()
    printer.print_message("Is the package an installer for executable(s)? {}"
                          .format(str(recipe_is_installer)))

    if not recipe_is_installer:
        recipe_is_unconditional_header_only = is_unconditional_header_only()
        printer.print_message("Is the package header only? {}"
                              .format(str(recipe_is_unconditional_header_only)))

        if not recipe_is_unconditional_header_only:
            recipe_is_conditional_header_only = is_conditional_header_only()
            printer.print_message("Is the package conditionally header only ('header_only' option)? {}"
                                  .format(str(recipe_is_conditional_header_only)))

            recipe_is_pure_c = is_pure_c()
            printer.print_message("Is the package C-only? {}".format(str(recipe_is_pure_c)))

    _flush_output()

    if recipe_is_installer:
        arch = os.getenv("ARCH", "x86_64")
        builder = build_template_installer.get_builder()
        builder.add({"os": get_os(), "arch_build": arch, "arch": arch}, {}, {}, {})
        builder.run()
    elif recipe_is_unconditional_header_only:
        builder = build_template_header_only.get_builder()
        builder.run()
    else:
        builder = build_template_default.get_builder(pure_c=recipe_is_pure_c)
        builder.run()


"""
Unit test for the executions endpoints
"""

# Import from libraries
import json

# Import from internal modules
from cornflow.models import ExecutionModel, InstanceModel
from cornflow.tests.const import (
    INSTANCE_PATH,
    EXECUTION_PATH,
    EXECUTIONS_LIST,
    EXECUTION_URL,
    EXECUTION_URL_NORUN,
    INSTANCE_URL,
)
from cornflow.tests.custom_test_case import CustomTestCase, BaseTestCases

class TestExecutionsListEndpoint(BaseTestCases.ListFilters):
    def setUp(self):
        super().setUp()

        with open(INSTANCE_PATH) as f:
            payload = json.load(f)
        fk_id = self.create_new_row(INSTANCE_URL, InstanceModel, payload)
        self.url = EXECUTION_URL_NORUN
        self.model = ExecutionModel

        def load_file_fk(_file):
            with open(_file) as f:
                temp = json.load(f)
            temp["instance_id"] = fk_id
            return temp

        self.payload = load_file_fk(EXECUTION_PATH)
        self.payloads = [load_file_fk(f) for f in EXECUTIONS_LIST]

    def test_new_execution(self):
        self.create_new_row(self.url, self.model, payload=self.payload)

    def test_new_execution_no_instance(self):
        payload = dict(self.payload)
        payload["instance_id"] = "bad_id"
        response = self.client.post(
            self.url,
            data=json.dumps(payload),
            follow_redirects=True,
            headers=self.get_header_with_auth(self.token),
        )
        self.assertEqual(404, response.status_code)
        self.assertTrue("error" in response.json)

    def test_get_executions(self):
        self.get_rows(self.url, self.payloads)

    def test_get_no_executions(self):
        self.get_no_rows(self.url)

    def test_get_executions_superadmin(self):
        self.get_rows(self.url, self.payloads)
        token = self.create_service_user()
        rows = self.client.get(
            self.url, follow_redirects=True, headers=self.get_header_with_auth(token)
        )
        self.assertEqual(len(rows.json), len(self.payloads))

class TestExecutionsDetailEndpointMock(CustomTestCase):
    def setUp(self):
        super().setUp()
        with open(INSTANCE_PATH) as f:
            payload = json.load(f)
        fk_id = self.create_new_row(INSTANCE_URL, InstanceModel, payload)
        self.model = ExecutionModel
        self.response_items = {
            "id",
            "name",
            "description",
            "created_at",
            "instance_id",
            "data_hash",
            "message",
            "state",
            "config",
            "schema",
            "user_id",
        }
        # we only check the following because this endpoint does not return data
        self.items_to_check = ["name", "description"]
        self.url = EXECUTION_URL
        with open(EXECUTION_PATH) as f:
            self.payload = json.load(f)
        self.payload["instance_id"] = fk_id

class TestExecutionsDetailEndpoint(
    TestExecutionsDetailEndpointMock, BaseTestCases.DetailEndpoint
):
    def setUp(self):
        super().setUp()
        self.url = self.url
        self.query_arguments = {"run": 0}

    # TODO: this test should be moved as it is not using the detail endpoint
    def test_incomplete_payload2(self):
        payload = {"description": "arg", "instance_id": self.payload["instance_id"]}
        response = self.create_new_row(
            self.url + "?run=0",
            self.model,
            payload,
            expected_status=400,
            check_payload=False,
        )

    def test_create_delete_instance_load(self):
        idx = self.create_new_row(self.url + "?run=0", self.model, self.payload)
        execution = self.get_one_row(
            self.url + idx, payload={**self.payload, **dict(id=idx)}
        )
        self.delete_row(self.url + idx + "/")
        instance = self.get_one_row(
            INSTANCE_URL + execution["instance_id"] + "/",
            payload={},
            expected_status=200,
            check_payload=False,
        )
        executions = [execution["id"] for execution in instance["executions"]]
        self.assertFalse(idx in executions)

    def test_delete_instance_deletes_execution(self):
        # we create a new instance
        with open(INSTANCE_PATH) as f:
            payload = json.load(f)
        fk_id = self.create_new_row(INSTANCE_URL, InstanceModel, payload)
        payload = {**self.payload, **dict(instance_id=fk_id)}
        # we create an execution for that instance
        idx = self.create_new_row(self.url + "?run=0", self.model, payload)
        self.get_one_row(self.url + idx, payload={**self.payload, **dict(id=idx)})
        # we delete the new instance
        self.delete_row(INSTANCE_URL + fk_id + "/")
        # we check the execution does not exist
        self.get_one_row(
            self.url + idx, payload={}, expected_status=404, check_payload=False
        )

class TestExecutionsDataEndpoint(TestExecutionsDetailEndpointMock):
    def setUp(self):
        super().setUp()
        self.response_items = {"id", "name", "data"}
        self.items_to_check = ["name"]

    def test_get_one_execution(self):
        idx = self.create_new_row(EXECUTION_URL_NORUN, self.model, self.payload)
        self.url = EXECUTION_URL + idx + "/data/"
        payload = dict(self.payload)
        payload["id"] = idx
        self.get_one_row(self.url, payload)

    def test_get_one_execution_superadmin(self):
        idx = self.create_new_row(EXECUTION_URL_NORUN, self.model, self.payload)
        payload = dict(self.payload)
        payload["id"] = idx
        token = self.create_service_user()
        self.get_one_row(EXECUTION_URL + idx + "/data/", payload, token=token)

class TestExecutionsLogEndpoint(TestExecutionsDetailEndpointMock):
    def setUp(self):
        super().setUp()
        self.response_items = {"id", "name", "log"}
        self.items_to_check = ["name"]

    def test_get_one_execution(self):
        idx = self.create_new_row(EXECUTION_URL_NORUN, self.model, self.payload)
        payload = dict(self.payload)
        payload["id"] = idx
        self.get_one_row(EXECUTION_URL + idx + "/log/", payload)

    def test_get_one_execution_superadmin(self):
        idx = self.create_new_row(EXECUTION_URL_NORUN, self.model, self.payload)
        payload = dict(self.payload)
        payload["id"] = idx
        token = self.create_service_user()
        self.get_one_row(EXECUTION_URL + idx + "/log/", payload, token=token)

class TestExecutionsModel(TestExecutionsDetailEndpointMock):
    def test_repr_method(self):
        idx = self.create_new_row(self.url + "?run=0", self.model, self.payload)
        self.repr_method(idx, "<id {}>".format(idx))

    def test_str_method(self):
        idx = self.create_new_row(self.url + "?run=0", self.model, self.payload)
        self.str_method(idx, "<id {}>".format(idx))


# pylint: disable=E1101

import mediapipe as mp
import cv2

mp_drawing = mp.solutions.drawing_utils
mp_holistic = mp.solutions.holistic

# Get realtime webcam feed
cap = cv2.VideoCapture("tommyinnit.mp4")
with mp_holistic.Holistic(
        min_detection_confidence=0.5, min_tracking_confidence=0.5
) as holistic:
    while cap.isOpened():
        ret, frame = cap.read()

        # Recolor feed
        img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # Make detections
        results = holistic.process(img)
        print(results.face_landmarks)

        # convert back to bgr
        image = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        # Draw face landmarks
        mp_drawing.draw_landmarks(
            image,
            results.face_landmarks,
            mp_holistic.FACE_CONNECTIONS
        )

        mp_drawing.draw_landmarks(
            image,
            results.pose_landmarks,
            mp_holistic.POSE_CONNECTIONS
        )

        cv2.imshow("Model detections", image)

        if cv2.waitKey(10) & 0xFF == ord("q"):
            break

cap.release()
cv2.destroyAllWindows()


# !/usr/bin/env python
# coding: utf-8
from base.base_model import BaseModel
import tensorflow as tf
from tensorflow.contrib import rnn

# 双向LSTM分词模型
class Bi_LSTM_crf(BaseModel):
    def __init__(self, config):
        super(Bi_LSTM_crf, self).__init__(config)
        self.X = None
        self.y = None
        self.time_step_size = config['time_step_size']
        self.vocab_size = config['vocab_size']
        self.embedding_size = config['embedding_size']
        self.hidden_size = config['hidden_size']
        self.layer_num = config['layer_num']
        self.class_num = config['class_num']
        self.reset_default_graph = config['reset_default_graph']
        self.max_to_keep = config['max_to_keep']
        # self.keep_prob = config['keep_prob']
        self.keep_prob = tf.placeholder(tf.float32, [], name='keep_prob')
        self.lr = tf.placeholder(tf.float32, name='learning_rate')
        self.batch_size = tf.placeholder(tf.int32, [], name='batch_size')
        self.build_model()
        self.init_saver()

    def build_model(self):
        # here you build the tensorflow graph of any model you want and also define the loss.
        # self.is_training = tf.placeholder(tf.bool, name='training')

        with tf.variable_scope('Inputs'):
            self.X = tf.placeholder(tf.int32, [None, self.time_step_size], name='X_input')
            self.y = tf.placeholder(tf.int32, [None, self.time_step_size], name='y_input')
            self.length = tf.reduce_sum(tf.sign(self.X), reduction_indices=1)
            self.length = tf.cast(self.length, tf.int32)

        bilstm_output = self.bi_lstm(self.X)

        with tf.name_scope('softmax'):
            with tf.name_scope('weight'):
                weights = self.weight_variables([self.hidden_size * 2, self.class_num])
                self.variable_summaries(weights)
            with tf.name_scope('bias'):
                biases = self.bias_variables([self.class_num])
                self.variable_summaries(biases)
            with tf.name_scope('linear'):
                preactivate = tf.matmul(bilstm_output, weights) + biases
                print(preactivate.shape)
                tf.summary.histogram('linear', preactivate)
                # preactivate.shape = [batchsize, timestepsize, classnum]
                #   将线性输出经过激励函数，并将输出也用直方图记录下来
            # with tf.name_scope('activation'):
            # activations = tf.nn.softmax(preactivate, name='activation')
            # tf.summary.histogram('activations', activations)

        self.preactive = tf.reshape(preactivate, [self.batch_size, self.time_step_size, self.class_num])
        with tf.name_scope('CRF'):
            self.log_likelihood, self.transition_params = tf.contrib.crf.crf_log_likelihood(self.preactive, self.y, self.length)
            self.batch_pred_sequence, self.batch_viterbi_score = tf.contrib.crf.crf_decode(
                self.preactive, self.transition_params, self.length)
            self.loss = tf.reduce_mean(-self.log_likelihood)
            summary = tf.summary.scalar("loss", self.loss)

        with tf.name_scope('Optimizer'):
            optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
            tf.summary.scalar('learning_rate', self.lr)
            self.opt = optimizer.minimize(self.loss, global_step=self.global_step_tensor)
        # summaries合并
        self.merged = tf.summary.merge_all()
        print('Finished creating the bi-lstm model.')
        pass

    def init_saver(self):
        # here you initialize the tensorflow saver that will be used in saving the checkpoints.
        self.saver = tf.train.Saver(max_to_keep=self.max_to_keep)
        pass

    @staticmethod
    def weight_variables(shape):
        """Create a weight variable with appropriate initialization."""
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial)

    @staticmethod
    def bias_variables(shape):
        """Create a bias variable with appropriate initialization."""
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)

    def lstm_cell_dropout(self, lstm_size, keep_prob):
        lstm = tf.nn.rnn_cell.LSTMCell(lstm_size, state_is_tuple=True)
        with tf.name_scope('dropout'):
            tf.summary.scalar('dropout_keep_probablity', self.keep_prob)
            drop = tf.nn.rnn_cell.DropoutWrapper(lstm, input_keep_prob=1.0, output_keep_prob=self.keep_prob)
        return drop

    def variable_summaries(self, var):
        """Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
        with tf.name_scope('summaries'):
            #       计算参数的均值，并使用tf.summary.scaler记录
            mean = tf.reduce_mean(var)
            tf.summary.scalar('mean', mean)

        #       计算参数的标准差
        with tf.name_scope('stddev'):
            stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
            #       使用tf.summary.scaler记录记录下标准差，最大值，最小值
            tf.summary.scalar('stddev', stddev)
            tf.summary.scalar('max', tf.reduce_max(var))
            tf.summary.scalar('min', tf.reduce_min(var))
            #       用直方图记录参数的分布
            tf.summary.histogram('histogram', var)

    def bi_lstm(self, X_inputs):
        """build the bi-LSTMs network. Return the y_pred"""

        # batch_size = tf.placeholder(tf.int32, [])  # 注意类型必须为 tf.int32
        with tf.name_scope("embedding"):
            embedding = tf.get_variable("embedding", [self.vocab_size, self.embedding_size], dtype=tf.float32)
        inputs = tf.nn.embedding_lookup(embedding, self.X)
        # inputs.shape=[batchsize, timestepsize, embeddingsize]

        # with tf.name_scope('lstm_cell'):

        with tf.name_scope('bi_lstm'):
            cell_fw = tf.nn.rnn_cell.MultiRNNCell(
                [self.lstm_cell_dropout(self.hidden_size, self.keep_prob) for _ in range(self.layer_num)],
                state_is_tuple=True)
            cell_bw = tf.nn.rnn_cell.MultiRNNCell(
                [self.lstm_cell_dropout(self.hidden_size, self.keep_prob) for _ in range(self.layer_num)],
                state_is_tuple=True)
            initial_state_fw = cell_fw.zero_state(self.batch_size, tf.float32)
            initial_state_bw = cell_bw.zero_state(self.batch_size, tf.float32)
            # inputs.shape= list of tensor, each tensor's shape = [batch_size, embedding_size]
            inputs = tf.unstack(inputs, self.time_step_size, 1)
            # try:
            outputs, _, _ = rnn.static_bidirectional_rnn(cell_fw, cell_bw, inputs,
                                                         initial_state_fw=initial_state_fw,
                                                         initial_state_bw=initial_state_bw, dtype=tf.float32)
            # except Exception:
            #     #     Old TensorFlow version only returns outputs not states
            #     outputs = rnn.static_bidirectional_rnn(cell_fw, cell_bw, inputs,
            #                                            initial_state_fw=initial_state_fw,
            #                                            initial_state_bw=initial_state_bw, dtype=tf.float32)
            outputs = tf.concat(outputs, 1)
            lstm_output = tf.reshape(outputs, [self.batch_size, self.time_step_size, self.hidden_size * 2])
            print(lstm_output.shape)
            # lstm_output.shape=list of tensor, each tensor's shape =[batch_size, 2 * hidden_size]
            lstm_out = tf.reshape(lstm_output, [-1, self.hidden_size * 2])
        return lstm_out  # [-1, hidden_size*2]


# COMP9021 19T3 - Rachid Hamadi
# Quiz 3 *** Due Thursday Week 4

# Reading the number written in base 8 from right to left,
# keeping the leading 0's, if any:
# 0: move N     1: move NE    2: move E     3: move SE
# 4: move S     5: move SW    6: move W     7: move NW
#
# We start from a position that is the unique position
# where the switch is on.
#
# Moving to a position switches on to off, off to on there.

import sys

on = '\u26aa' #(白圈)
off = '\u26ab' #（黑圈）
code = input('Enter a non-strictly negative integer: ').strip()
try:
    if code[0] == '-':
        raise ValueError
    int(code)
except ValueError:
    print('Incorrect input, giving up.')
    sys.exit()
nb_of_leading_zeroes = 0
for i in range(len(code) - 1):
    if code[i] == '0':
        nb_of_leading_zeroes += 1
    else:
        break
print("Keeping leading 0's, if any, in base 8,", code, 'reads as',
      '0' * nb_of_leading_zeroes + f'{int(code):o}.'
     )
print()

# INSERT YOUR CODE HERE
number = '0' * nb_of_leading_zeroes + f'{int(code):o}.'
#print(number)
number_list = []

#print(begin)
for i in range(len(number)):
    #print(number[i])
    number_list.append(number[i])
#print(number_list)
del number_list[-1]
#print(number_list)
number_list = list(reversed(number_list))
number_list = list(map(int, number_list))
#print(number_list)

all_number =[(0,0)]
x,y = 0,0
for i in number_list:
    if i == 0:
        x = x
        y = y + 1
        all_number.append((x,y))
    elif i == 1:
        x = x + 1
        y = y + 1
        all_number.append((x,y))
    elif i == 2:
        x = x + 1
        y = y
        all_number.append((x,y))
    elif i ==3:
        x = x + 1
        y = y - 1
        all_number.append((x,y))
    elif i ==4:
        x = x
        y = y - 1
        all_number.append((x,y))
    elif i ==5:
        x = x -1
        y = y -1
        all_number.append((x,y))
    elif i ==6:
        x = x -1
        y = y
        all_number.append((x,y))
    elif i ==7:
        x = x - 1
        y = y + 1
        all_number.append((x,y))
#print(all_number)

B = []
C = []
a1 = []
for i in range(len(all_number)):
    if all_number.count(all_number[i]) % 2 == 0:
        B.append(all_number[i])
#print(B)
for y in all_number:
    if y not in B or y in a1:
        C.append(y)
        a1 = sorted(set(C),key=C.index)
#print('C',C)
#print('delete multiple:',a1)

if len(a1) != 0:
    x_row, y_cloum = zip(*a1)
    x_row = sorted(set(sorted(x_row)),key=sorted(x_row).index)
    y_cloum =list(reversed(sorted(set(sorted(y_cloum)),key=sorted(y_cloum).index)))
    x_row_count = [i for i in range(x_row[0],x_row[-1]+1)]
    y_cloum_count = list(reversed([j for j in range(y_cloum[-1],y_cloum[0]+1)]))
    print(x_row_count)
    print(y_cloum_count)

    print('x_row',x_row)
    print('y_cloum',y_cloum)

    for y in y_cloum_count:
        for x in x_row_count:
            if(x,y) not in a1:
                print(off,end ='')
            else:
                print(on,end ='')
        print()
input('qewsdss')


"""A dataset which returns a random tensor."""

import torch
import torch.utils.data as data
import torchvision.datasets.vision
import os
import os.path
import numpy as np
import sys

if sys.version_info[0] == 2:
    import cPickle as pickle
else:
    import pickle

def is_positive_integer(value):
    if not(isinstance(value, int)):
        return False
    try:
        tmp = int(value)
    except ValueError:
        return False
    if not value > 0:
        return False
    return True

class RandomDataset(data.Dataset):
    """RandomDataset.

     Args:
         batch_size (integer): Number of samples in the batch.
         sample_size (integer): Size of the sample.
         shape (tuple): The shape in (rows, cols) of the random data to be returned.
         transform (callable, optional): A function/transform that takes in an PIL image
             and returns a transformed version. E.g, ``transforms.RandomCrop``
         target_transform (callable, optional): A function/transform that takes in the
             target and transforms it.

    Typical usage:
        from dcgan.random_dataset import RandomDataset
        rando = random_dataset.RandomDataset(batch_size, 10)

        for i, data in enumerate(rando):
            print('Iteration: ', i)
            print('Data:      ', data)

     """
    # usually these guys have a root directory, but we're not relying on
    # any of yer actual files ...

    def __init__(self, batch_size, sample_size, transforms=None, transform=None, target_transform=None):

        if not is_positive_integer(batch_size) or not is_positive_integer(sample_size):
            raise RuntimeError('Paramaters batch_size and/or sample_size must be positive integers.' +
                               ' Both must be greater than zero')

        self.batch_size = batch_size
        self.sample_size = sample_size

        has_transforms = transforms is not None
        has_separate_transform = transform is not None or target_transform is not None
        if has_transforms and has_separate_transform:
            raise ValueError("Only transforms or transform/target_transform can "
                             "be passed as argument")

        # for backwards-compatibility
        self.transform = transform
        self.target_transform = target_transform

        if has_separate_transform:
            transforms = torchvision.StandardTransform(transform, target_transform)
        self.transforms = transforms

    def __getitem__(self, index):
        """
        Args:
            index (int): Index

        Returns:
            tensor: tensor of m random numbers.
        """
        return torch.rand(self.batch_size, self.sample_size)

    def __len__(self):
        return self.sample_size

    # def __repr__(self): ... should be inherited from the parent class
    # ... so it's worth testing to see if it works ...from


import time

while True:
    userInput = input(">> ")
    try:
        when_to_stop = abs(int(userInput))
    except KeyboardInterrupt:
        break
    except:
        print("Not a number.")
    while when_to_stop >= 0:
        min, sec = divmod(when_to_stop, 60)
        hour, min = divmod(min, 60)
        time.sleep(1)
        time_left = "{:02}:{:02}:{:02}".format(hour, min, sec)
        print(time_left +"\r", end="")
        when_to_stop-=1
    print()


"""
This module defines Admin models to map our Category and Item models so that
they can be managed via the Django admin page /admin
"""
from django.contrib import admin
from django.db import models
from tinymce.widgets import TinyMCE

from .models import Category, Item

class ItemAdmin(admin.ModelAdmin):
    """
    Class to add an Item from the Django admin page with the TinyMCE
    plugin which provides text formatting options
    """

    fieldsets = [
        ("Title/date", {"fields": ["item_name", "date_published"]}),
        ("URL", {"fields": ["item_slug"]}),
        ("Parent Element", {"fields": ["category_name"]}),
        ("Content (Width ~600px)", {"fields": ["summary", "content"]}),
    ]
    # Add TinyMCE Widget to textfield property
    formfield_overrides = {
        models.TextField: {"widget": TinyMCE()},
    }

class CategoryAdmin(admin.ModelAdmin):
    """Class to add a Category from the Django admin page."""

    fieldsets = [
        (
            "Category details",
            {"fields": ["category_name", "summary", "image", "category_slug"]},
        )
    ]

# Register models
admin.site.register(Item, ItemAdmin)
admin.site.register(Category, CategoryAdmin)