# -*- coding: utf-8 -*-
"""
Created on Sat Oct  8 13:45:38 2022

@author: mzeigha
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm
import seaborn as sns
from textwrap import wrap
import matplotlib.colors as colors

production_no_tax = pd.read_parquet('Results/production_df_no_tax.parquet')
# production_SNP = pd.read_parquet('Results/production_df_SNP.parquet')

generators = pd.read_csv('Results/generators.csv',index_col=0 )
county_damage_per_generator = pd.read_csv('Results/county_damage_per_generator.csv', index_col=0).T
county_damage_per_generator = county_damage_per_generator[15:73]

population = pd.read_csv('Results/USA_Counties/white_population.csv')
population["non_white"] = (population['P1_001N']-population['P1_003N'])/population['P1_001N']

for i in range(len(population)):
    population.loc[i,'county'] = str(population.loc[i,'GEO_ID'])[-5:]
population.index = population['county']

egrid = pd.read_csv('C:/Users/mzeigha/Documents/GitHub/CAPOW_Emission/Generator/eGRID Plants.csv', dtype = str)
gen = pd.read_csv('C:/Users/mzeigha/Documents/GitHub/CAPOW_Emission/Generator/generator_final_DOE.csv', index_col=('name'))

for i in gen.index:
    a = egrid[egrid['ORISPL']==str(gen.loc[i,'DOE'])]

    try:
        gen.loc[i,'county2'] = a.iloc[0,16] + a.iloc[0,17]
    except Exception:
        pass

generators = pd.concat([generators,gen['county2']], axis = 1)

for i in generators.index:

    if generators.loc[i,'zone'] == 'PGE_valley':
        generators.loc[i,'gas'] = 4.66

    elif generators.loc[i,'zone']=='PGE_bay':
        generators.loc[i,'gas'] = 4.66

    else:
        generators.loc[i,'gas'] = 4.47

generators['no_tax_cost'] =generators['gas']*generators['seg2']+generators['var_om']

generators = generators.sort_values(by = 'no_tax_cost')

M = pd.DataFrame([])
for i in generators.index:
    for j in population.index:
        if generators.loc[i, 'county2'] == str(j):
            M.loc[i,j] = generators.loc[i,'NOXTax'] + generators.loc[i,'SO2Tax'] + generators.loc[i,'PMTax']
        else:
            M.loc[i,j] = 0

no_tax= production_no_tax.groupby(['Year'])[generators.index].sum()
# SNP= production_SNP.groupby(['Year'])[generators.index].sum()

portion = ((county_damage_per_generator.T).loc[generators.index]).T

no_tax_damage = {}
# SNP_damage = {}
for i in range(500):
    no_tax_damage[i] = (portion*no_tax.loc[i])
    # SNP_damage[i] = (county_damage_per_generator*SNP.loc[i]).T

no_tax_damage_avg = (portion*no_tax.sum()/500).T
# SNP_damage_avg = county_damage_per_generator*SNP.sum()/500

# M2 = pd.DataFrame([])
# for i in generators.index:
#     for j in population.index:
#         if generators.loc[i, 'county2'] == str(j):
#             M2.loc[i,j] = no_tax_damage_avg.loc[i,j]
#         # else:
#         #     M2.loc[i,j] = 0

#%%
amir = pd.DataFrame([])
for i in range (500):
    amir.loc[i, 'sum'] = no_tax_damage[i].sum().sum()

#%%

# M3 = pd.DataFrame([])
# for i in generators.index:
#     for j in population.index:
#         if generators.loc[i, 'county2'] == str(j):
#             M3.loc[i,j] = no_tax_damage[151].loc[i,j]
#         # else:
#         #     M3.loc[i,j] = 0

M2 = no_tax_damage_avg
M3 = no_tax_damage[151].T
M4 = M3-M2

xcsfont = {'fontname':'arial' , 'fontweight':'bold'}
csfont = {'fontname':'arial'}

fig = plt.figure( figsize = (15,10))

gs = fig.add_gridspec(4,1, width_ratios=[1], height_ratios = [1, 1, 1, 1] , wspace=0, hspace=0.3 )

############# Wind
cf_ax1 = fig.add_subplot(gs[0,0])
cf_ax2 = fig.add_subplot(gs[1,0])
cf_ax3 = fig.add_subplot(gs[2,0])
cf_ax4 = fig.add_subplot(gs[3,0])

cmap1 = 'Reds'

A = pd.concat([M.T , population['non_white']], axis = 1)
A = A.sort_values(by = 'non_white')

ylabel = [np.round(A.iloc[0,-1],decimals=2), np.round(A.iloc[10,-1],decimals=2), np.round(A.iloc[20,-1],decimals=2), np.round(A.iloc[30,-1],decimals=2), np.round(A.iloc[40,-1],decimals=2),np.round(A.iloc[50,-1],decimals=2)]
yticks = [0,10,20,30,40,50]

xlabel = [np.round(generators.iloc[0,-1],decimals=2), np.round(generators.iloc[50,-1],decimals=2), np.round(generators.iloc[100,-1],decimals=2), np.round(generators.iloc[150,-1],decimals=2), np.round(generators.iloc[200,-1],decimals=2)]
xticks = [0,50,100,150,200]

A.index = A['non_white']
A = A.drop(columns = ['non_white'])

norm=colors.LogNorm(vmin = 1 , vmax = 100 )
cbar = plt.cm.ScalarMappable(norm=norm, cmap=cmap1)

a = cf_ax1.matshow(A, norm=norm, cmap=cmap1)
cf_ax1.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
cf_ax1.set_xticks( xticks, xlabel, fontsize=14, **csfont)
cf_ax1.xaxis.set_label_position('top')
cf_ax1.set_xlabel('a)',loc='left',labelpad = 6, fontsize=15, **xcsfont)
# cf_ax1.set_ylabel('SNP Tax',fontsize=16, **csfont)
cf_ax1.set_title('Power Plant (increasing Marginal Cost in $/MWh)',y = 1.2, fontsize=16, **csfont)
cf_ax1.axhline(32,color='black', linestyle='dotted')

cf_ax1.annotate('32 Majority white counties', (150,5),annotation_clip=False , fontsize=11,**csfont)
cf_ax1.annotate('26 Majority non-white counties', (140,37),annotation_clip=False , fontsize=11,**csfont)
cf_ax1.annotate('Non-White portion of County Population', (-32,210), rotation=90 , annotation_clip=False , fontsize=16,**csfont)

cax = plt.axes([0.72, 0.73, 0.02, 0.15])
cbar = plt.colorbar(a, cax= cax , orientation="vertical", ticks = [1,10,100] )#.set_ticklabels([3.13,8.58])
cbar.set_ticklabels([0, 10, 100])
cbar.ax.tick_params(labelsize=12)
cbar.set_label('\n'.join(wrap("Damage Rate ($/MWh)", 12)),labelpad=2,fontsize=14,**csfont)
# '\n'.join(wrap("Anomaly (C)", 12)),labelpad=15,fontsize=12,**csfont)

B = pd.concat([M2.T , population['non_white']], axis = 1)
B = B.sort_values(by = 'non_white')
B.index = B['non_white']
B = B.drop(columns = ['non_white'])
norm=colors.LogNorm(vmin=1, vmax=M3.max().max())
cbar = plt.cm.ScalarMappable(norm=norm, cmap=cmap1)

cf_ax2.matshow(B, norm = colors.LogNorm(), cmap=cmap1)
cf_ax2.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
cf_ax2.set_xticks([])
# cf_ax2.set_ylabel('Average Year',fontsize=16, **csfont)
# cf_ax2.set_title('Net Cap',fontsize=16, **csfont)
cf_ax2.xaxis.set_label_position('top')
cf_ax2.set_xlabel('b)',loc='left',labelpad = 6, fontsize=15, **xcsfont)

C = pd.concat([M3.T , population['non_white']], axis = 1)
C = C.sort_values(by = 'non_white')
C.index = C['non_white']
C = C.drop(columns = ['non_white'])

cf_ax3.matshow(C, norm = colors.LogNorm(), cmap=cmap1)
cf_ax3.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
cf_ax3.set_xticks([])
# cf_ax3.set_ylabel('Worst Year',fontsize=16, **csfont)
# cf_ax3.title('Net Cap')
cf_ax3.xaxis.set_label_position('top')
cf_ax3.set_xlabel('c)',loc='left',labelpad = 6, fontsize=15, **xcsfont)

cax2 = plt.axes([0.72, 0.33, 0.02, 0.34])
cbar = plt.colorbar(cbar, cax= cax2 , orientation="vertical")#, ticks = [1,100,200] )#.set_ticklabels([3.13,8.58])
# cbar.set_ticklabels([0, 10, 200])
cbar.ax.tick_params(labelsize=12)
cbar.set_label("Damage ($)",labelpad=2,fontsize=14,**csfont)

# norm= TwoSlopeNorm(vmin=M4.min().min(), vcenter=0, vmax=M4.max().max())

D = pd.concat([M4.T , population['non_white']], axis = 1)
D = D.sort_values(by = 'non_white')
D.index = D['non_white']
D = D.drop(columns = ['non_white'])

 # norm=colors.SymLogNorm
a = cf_ax4.matshow(D, norm = colors.LogNorm(), cmap=cmap1)
cf_ax4.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
cf_ax4.set_xticks([])
# cf_ax4.set_ylabel('Disparity',fontsize=16, **csfont)
cf_ax4.xaxis.set_label_position('top')
cf_ax4.set_xlabel('d)',loc='left',labelpad = 6, fontsize=15, **xcsfont)

# ylabel = [-10000, -100, 0 ,100,10000,1000000,100000000]
# yticks = [-10000, -100, 0 ,100,10000,1000000,100000000]

cax3 = plt.axes([0.72, 0.127, 0.02, 0.15])
cbar = plt.colorbar(a, cax= cax3 , orientation="vertical")#, ticks = [ 0, 100] )#.set_ticklabels([3.13,8.58])
# cbar.set_ticklabels(['-10000','','','','', '0','','','','','' ,'100000000'])
cbar.ax.tick_params(labelsize=13)
cbar.set_label("Damage ($)",labelpad=13,fontsize=14,**csfont)

# plt.savefig('Plots/REVIEW_MP2_1.png' , bbox_inches='tight',dpi=250)

# #%%
# N2 = SNP_damage_avg.T
# N3 = SNP_damage[151]
# N4 = N3-N2

# csfont = {'fontname':'arial'}

# fig = plt.figure( figsize = (15,10))

# gs = fig.add_gridspec(4,1, width_ratios=[1], height_ratios = [1, 1, 1, 1] , wspace=0, hspace=0.1 )

# ############# Wind
# cf_ax1 = fig.add_subplot(gs[0,0])
# cf_ax2 = fig.add_subplot(gs[1,0])
# cf_ax3 = fig.add_subplot(gs[2,0])
# cf_ax4 = fig.add_subplot(gs[3,0])

# A = pd.concat([M.T , population['non_white']], axis = 1)
# A = A.sort_values(by = 'non_white')

# ylabel = [np.round(A.iloc[0,-1],decimals=2), np.round(A.iloc[10,-1],decimals=2), np.round(A.iloc[20,-1],decimals=2), np.round(A.iloc[30,-1],decimals=2), np.round(A.iloc[40,-1],decimals=2),np.round(A.iloc[50,-1],decimals=2)]
# yticks = [0,10,20,30,40,50]

# xlabel = [np.round(generators.iloc[0,2],decimals=2), np.round(generators.iloc[50,2],decimals=2), np.round(generators.iloc[100,2],decimals=2), np.round(generators.iloc[150,2],decimals=2), np.round(generators.iloc[200,2],decimals=2)]
# xticks = [0,50,100,150,200]

# A.index = A['non_white']
# A = A.drop(columns = ['non_white'])

# norm=colors.LogNorm(vmin = 1 , vmax = A.max().max() )
# cbar = plt.cm.ScalarMappable(norm=norm, cmap='RdBu_r')

# cf_ax1.matshow(A, norm=colors.LogNorm(), cmap='RdBu_r')
# cf_ax1.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
# cf_ax1.set_xticks( xticks, xlabel ,fontsize=14, **csfont)
# cf_ax1.set_ylabel('SNP Tax',fontsize=16, **csfont)
# cf_ax1.set_title('Net Cap',fontsize=16, **csfont)
# cf_ax1.axhline(32,color='black', linestyle='dotted')

# cf_ax1.annotate('32 Majority white counties', (160,5),annotation_clip=False , fontsize=11,**csfont)
# cf_ax1.annotate('26 Majority non-white counties', (150,37),annotation_clip=False , fontsize=11,**csfont)

# cax = plt.axes([0.75, 0.705, 0.02, 0.17])
# cbar = plt.colorbar(cbar, cax= cax , orientation="vertical", ticks = [1,10,200] )#.set_ticklabels([3.13,8.58])
# cbar.set_ticklabels([0, 10, 200])
# cbar.ax.tick_params(labelsize=15)

# B = pd.concat([N2.T , population['non_white']], axis = 1)
# B = B.sort_values(by = 'non_white')
# B.index = B['non_white']
# B = B.drop(columns = ['non_white'])
# norm=colors.LogNorm(vmin=1, vmax=M3.max().max())
# cbar = plt.cm.ScalarMappable(norm=norm, cmap='RdBu_r')

# cf_ax2.matshow(B, norm = colors.LogNorm(), cmap='RdBu_r')
# cf_ax2.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
# cf_ax2.set_xticks([])
# cf_ax2.set_ylabel('Average Year',fontsize=16, **csfont)
# # cf_ax2.title('Net Cap')

# C = pd.concat([N3.T , population['non_white']], axis = 1)
# C = C.sort_values(by = 'non_white')
# C.index = C['non_white']
# C = C.drop(columns = ['non_white'])

# cf_ax3.matshow(C, norm = colors.LogNorm(), cmap='RdBu_r')
# cf_ax3.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
# cf_ax3.set_xticks([])
# cf_ax3.set_ylabel('Worst Year',fontsize=16, **csfont)
# # cf_ax3.title('Net Cap')

# cax2 = plt.axes([0.75, 0.33, 0.02, 0.35])
# cbar = plt.colorbar(cbar, cax= cax2 , orientation="vertical")#, ticks = [1,100,200] )#.set_ticklabels([3.13,8.58])
# # cbar.set_ticklabels([0, 10, 200])
# cbar.ax.tick_params(labelsize=15)

# norm= TwoSlopeNorm(vmin=N4.min().min(), vcenter=0, vmax=N4.max().max())
# cbar = plt.cm.ScalarMappable(norm=norm, cmap='RdBu_r')
# D = pd.concat([N4.T , population['non_white']], axis = 1)
# D = D.sort_values(by = 'non_white')
# D.index = D['non_white']
# D = D.drop(columns = ['non_white'])

# cf_ax4.matshow(D, norm = colors.LogNorm(), cmap='RdBu_r')
# cf_ax4.set_yticks( yticks, ylabel ,fontsize=14, **csfont)
# cf_ax4.set_xticks([])
# cf_ax4.set_ylabel('Worst Year',fontsize=16, **csfont)

# cax3 = plt.axes([0.75, 0.125, 0.02, 0.17])
# cbar = plt.colorbar(cbar, cax= cax3 , orientation="vertical")#, ticks = [1,10,200] )#.set_ticklabels([3.13,8.58])
# # cbar.set_ticklabels([0, 10, 200])
# cbar.ax.tick_params(labelsize=15)

# plt.savefig('Plots/REVIEW2_SNP.png' , bbox_inches='tight',dpi=250)


from config import config_object

default_bind_ip = "localhost"
doc = 'What interface to bind to.'
bind_ip = config_object.getOption('main.bind_ip', default_bind_ip, doc)

default_bind_port = 28787
doc = 'What port to bind to.'
bind_port = int(config_object.getOption('main.bind_port', default_bind_port, doc))

default_backlog_size = 5
doc = 'Max incoming connections to backlog.'
backlog_size = int(config_object.getOption('main.backlog_size', default_backlog_size, doc))

default_mumbleteam_enabled = True
doc = 'Enable connecting to the mumble team daemon.'
mumbleteam_enabled = config_object.getOption('mumbleteam.enabled', default_mumbleteam_enabled, doc)=="True"

default_mumbleteam_ip = "localhost"
doc = 'What ip to connect to the mumble team daemon on.'
mumbleteam_ip = config_object.getOption('mumbleteam.ip', default_mumbleteam_ip, doc)

default_mumbleteam_port = 28783
doc = 'What port to connect to the mumble team daemon on.'
mumbleteam_port = int(config_object.getOption('mumbleteam.port', default_mumbleteam_port, doc))

default_ircbot_enabled = True
doc = 'Enable connecting to the irc bot.'
ircbot_enabled = config_object.getOption('ircbot.enabled', default_ircbot_enabled, doc)=="True"

default_ircbot_ip = "localhost"
doc = 'What ip to connect to the irc bot on.'
ircbot_ip = config_object.getOption('ircbot.ip', default_ircbot_ip, doc)

default_ircbot_port = 28782
doc = 'What port to connect to the irc bot on.'
ircbot_port = int(config_object.getOption('ircbot.port', default_ircbot_port, doc))

del config_object

from Controller import Controller

controller = Controller(bind_ip, bind_port, backlog_size, mumbleteam_enabled, mumbleteam_ip, mumbleteam_port, ircbot_enabled, ircbot_ip, ircbot_port)


# Ty Bergstrom
# process.py
# CSCE A401
# August 2020
# Software Engineering Project
#
# Pre-process the dataset for any model

from sklearn.preprocessing import LabelBinarizer
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.preprocessing.image import img_to_array
from keras.utils import to_categorical
from imutils import paths
import numpy as np
import random
import cv2
import sys
import os

class Pprocess:

	# Load the input dataset and process
	def preprocess(dataset, HXW):
		data = []
		cl_labels = []
		img_paths = sorted(list(paths.list_images(dataset)))
		if len(img_paths) < 1:
			print("Err: No images found in:", dataset)
			sys.exit(1)
		random.seed(64)
		random.shuffle(img_paths)
		for img_path in img_paths:
			img = cv2.imread(img_path)
			img = cv2.resize(img, (HXW, HXW))
			img = img_to_array(img)
			data.append(img)
			label = img_path.split(os.path.sep)[-2]
			cl_labels.append(label)
		data = np.array(data, dtype="float") / 255.0
		if len(data) != len(cl_labels):
			print("Err: Data not correctly labeled with classes")
			sys.exit(1)
		return data, cl_labels

	# Processing required for the class labels to work
	def class_labels(cl_labels):
		lb = LabelBinarizer()
		cl_labels = lb.fit_transform(cl_labels)
		num_classes = len(lb.classes_)
		if num_classes < 2:
			print("Err: Not enough classes")
			sys.exit(1)
		return lb, cl_labels, num_classes

	# Loss type depending on how many classes
	def binary_or_categorical(num_classes):
		if num_classes > 2:
			return "categorical_crossentropy"
		return "binary_crossentropy"

	# sklearn train test split, with extra processing for binary classification
	def split(data, cl_labels, num_classes, test_size=0.2):
		cl_labels = np.array(cl_labels)
		(train_X, test_X, train_Y, test_Y) = train_test_split(
			data, cl_labels,
			test_size=test_size,
			random_state=64
		)
		if num_classes == 2:
			train_Y = to_categorical(train_Y, num_classes=num_classes)
			test_Y = to_categorical(test_Y, num_classes=num_classes)
		return train_X, test_X, train_Y, test_Y

	# Different options for augmentation pre-processing
	# Too much is bad, so these are rolled back to small incremental changes
	def data_aug(aug):
		wsr = 0.1
		hsr = 0.1
		if aug == "light1":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="nearest",
            rotation_range=15, shear_range=0.1, zoom_range=0.1,
            width_shift_range=wsr, height_shift_range=hsr)
		if aug == "light2":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="reflect",
            rotation_range=15, shear_range=0.1, zoom_range=0.1,
            width_shift_range=wsr, height_shift_range=hsr)
		if aug == "light3":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="wrap",
            rotation_range=15, shear_range=0.1, zoom_range=0.1,
            width_shift_range=wsr, height_shift_range=hsr)

		if aug == "medium1":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="nearest",
            rotation_range=30, shear_range=0.2, zoom_range=0.2,
            width_shift_range=wsr, height_shift_range=hsr)
		if aug == "medium2":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="reflect",
            rotation_range=30, shear_range=0.2, zoom_range=0.2,
            width_shift_range=wsr, height_shift_range=hsr)
		if aug == "medium3":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="wrap",
            rotation_range=30, shear_range=0.2, zoom_range=0.2,
            width_shift_range=wsr, height_shift_range=hsr)

		if aug == "heavy1":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="reflect",
            rotation_range=45, shear_range=0.2, zoom_range=0.3,
            width_shift_range=wsr, height_shift_range=hsr)
		if aug == "heavy2":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="nearest",
            rotation_range=45, shear_range=0.2, zoom_range=0.3,
            width_shift_range=wsr, height_shift_range=hsr)
		if aug == "heavy3":
			return ImageDataGenerator(horizontal_flip=True, fill_mode="wrap",
            rotation_range=45, shear_range=0.2, zoom_range=0.3,
            width_shift_range=wsr, height_shift_range=hsr)

		else:
			return ImageDataGenerator(horizontal_flip=True, fill_mode="nearest",
            rotation_range=30, shear_range=0.2, zoom_range=0.2,
            width_shift_range=wsr, height_shift_range=hsr)

##


from django.urls import path
from .views import  *

urlpatterns = [
    path('create-credit', create_credit_view, name='create-credit'),
    path('view-my-credit', view_my_credit, name='view my credits'),
    path('update-credit/<int:pk>', update_credit_view, name='update-credit'),
    path('delete-my-credit', delete_credit_view, name='delete-credit'),
    ]


# 탑

n = int(input())
data = list(map(int, input().split(' ')))
stack = []
result = []

for index, value in enumerate(data):
    while True:
        if len(stack) == 0:
            result.append(0)
            break
        if stack[-1][1] > value:
            result.append(stack[-1][0] + 1)
            break
        else:
            stack.pop()
    stack.append([index, value])

for i in result:
    print(i, end=' ')


import unittest

from pyspark.ml.pipeline import Pipeline
from pyspark.testing.mlutils import MockDataset, MockEstimator, MockTransformer, PySparkTestCase

class PipelineTests(PySparkTestCase):

    def test_pipeline(self):
        dataset = MockDataset()
        estimator0 = MockEstimator()
        transformer1 = MockTransformer()
        estimator2 = MockEstimator()
        transformer3 = MockTransformer()
        pipeline = Pipeline(stages=[estimator0, transformer1, estimator2, transformer3])
        pipeline_model = pipeline.fit(dataset, {estimator0.fake: 0, transformer1.fake: 1})
        model0, transformer1, model2, transformer3 = pipeline_model.stages
        self.assertEqual(0, model0.dataset_index)
        self.assertEqual(0, model0.getFake())
        self.assertEqual(1, transformer1.dataset_index)
        self.assertEqual(1, transformer1.getFake())
        self.assertEqual(2, dataset.index)
        self.assertIsNone(model2.dataset_index, "The last model shouldn't be called in fit.")
        self.assertIsNone(transformer3.dataset_index,
                          "The last transformer shouldn't be called in fit.")
        dataset = pipeline_model.transform(dataset)
        self.assertEqual(2, model0.dataset_index)
        self.assertEqual(3, transformer1.dataset_index)
        self.assertEqual(4, model2.dataset_index)
        self.assertEqual(5, transformer3.dataset_index)
        self.assertEqual(6, dataset.index)

    def test_identity_pipeline(self):
        dataset = MockDataset()

        def doTransform(pipeline):
            pipeline_model = pipeline.fit(dataset)
            return pipeline_model.transform(dataset)
        # check that empty pipeline did not perform any transformation
        self.assertEqual(dataset.index, doTransform(Pipeline(stages=[])).index)
        # check that failure to set stages param will raise KeyError for missing param
        self.assertRaises(KeyError, lambda: doTransform(Pipeline()))

if __name__ == "__main__":
    from pyspark.ml.tests.test_pipeline import *  # noqa: F401

    try:
        import xmlrunner  # type: ignore[import]
        testRunner = xmlrunner.XMLTestRunner(output='target/test-reports', verbosity=2)
    except ImportError:
        testRunner = None
    unittest.main(testRunner=testRunner, verbosity=2)


import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium import webdriver

class SearchCustomer():
    # Add Customer Page
    txt_email_Xpath = "//*[@id='SearchEmail']"
    txt_firstName_Xpath = "//*[@id='SearchFirstName']"
    txt_lastName_Xpath = "//*[@id='SearchLastName']"
    btn_search_Xpath = "//*[@id='search-customers']"
    table_Xpath = "//*[@id='customers-grid_wrapper']/div[1]/div"
    tabel_rows_Xpath = "//*[@id='customers-grid']//tbody//tr"
    table_column_Xpath = "//*[@id='customers-grid']//tbody//tr//td"

    def __init__(self,driver):
        self.driver = driver

    def setEmail(self,email):
        self.driver.find_element(By.XPATH, self.txt_email_Xpath).clear()
        self.driver.find_element(By.XPATH, self.txt_email_Xpath).send_keys(email)

    def setFirstName(self,fname):
        self.driver.find_element(By.XPATH, self.txt_firstName_Xpath).clear()
        self.driver.find_element(By.XPATH, self.txt_firstName_Xpath).send_keys(fname)

    def setLastName(self,lname):
        self.driver.find_element(By.XPATH, self.txt_lastName_Xpath).clear()
        self.driver.find_element(By.XPATH, self.txt_lastName_Xpath).send_keys(lname)

    def clickSearch(self):
        self.driver.find_element(By.XPATH, self.btn_search_Xpath).click()

    def getNoRows(self):
        return len(self.driver.find_elements(By.XPATH,self.tabel_rows_Xpath))

    def getNoColumns(self):
        return len(self.driver.find_elements(By.XPATH,self.table_column_Xpath))

    def searchCustomerByEmail(self,email):
        flag = False
        for r in range(1,self.getNoRows()+1):
           table =  self.driver.find_element(By.XPATH,self.table_Xpath)
           emailId = table.find_element(By.XPATH,"//*[@id='customers-grid']/tbody/tr["+ str(r) +"]/td[2]").text
           if emailId == email:
               flag = True
               break
        return flag

    def searchCustomerByName(self,Name):
        flag = False
        for r in range(1,self.getNoRows()+1):
           table =  self.driver.find_element(By.XPATH,self.table_Xpath)
           name = table.find_element(By.XPATH,"//*[@id='customers-grid']/tbody/tr[" +str(r) + "]/td[3]").text
           if name == Name:
               flag = True
               break
        return flag


#!/usr/local/bin/python3.6

import json
import subprocess
import sys

CONST = {
    "hyperparameters_config": "/opt/ml/input/config/hyperparameters.json"
}

def launch_training():

    # Read info that SageMaker provides
    hc_path = CONST["hyperparameters_config"]
    exitcode = 0

    try:
        with open(hc_path, 'r') as f:
            hyperparamters = json.load(f)
            train_script = hyperparamters["train_script"]
            print(f"Hyperparameter train_script: {train_script}")

            subprocess.check_call(f"chmod u+x {train_script}",  shell=True)
            process = subprocess.Popen([train_script], encoding='utf-8', stdout=subprocess.PIPE)

            while True:
                if process.poll() != None:
                    break
                output = process.stdout.readline()
                if output:
                    print(output.strip())

            exitcode = process.poll()
            print(f"Training script exit code: {exitcode}")
    except Exception as e:
        print("Launch training exception occured")
        exitcode = 1
        print(str(e))

    sys.exit(exitcode)

if __name__ == "__main__":
    launch_training()


'''
BoJ 20055   Gold 5  implementation
'''
N, K = map(int, input().split())
durability = list(map(int, input().split()))
robot = [0] * N

step = 0

while durability.count(0) < K:
    durability.insert(0, durability.pop())  # 1.회전
    robot.insert(0, robot.pop())            # 1.회전

    if robot[N-1] != 0:
        robot[N-1] = 0

    for i in range(N-1, -1, -1):
        if robot[i] == 1:
            if durability[i+1] > 0 and robot[i+1] == 0:
                robot[i] = 0
                robot[i+1] = 1
                durability[i+1] -= 1

    if robot[N-1] != 0:
        robot[N-1] = 0

    if durability[0] > 0:
        robot[0] = 1
        durability[0] -= 1
    step += 1

print(step)


'''
This module is to show how unit testing works using the unittest library.
Testing the functions that interact with MySQL would require mocking a database.
'''

import os, sys
import unittest
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)
from part_2 import build_report_string

class SomeTests(unittest.TestCase):

    def test_build_report_string(self):
        mock_input = ['US','CA',-10,20]
        self.assertEqual(build_report_string(mock_input),\
                         'The minimum and maximum temperatures in CA between 1990 and 2000 were respectively -10 and 20.')

if __name__ == '__main__':
    unittest.main()


motorcycles = ["Pulsar220", "BMW", "Ducati","Honda" ]
motorcycles.sort()     #To organize
print(motorcycles)
print("\n")

message = "My first bike was " + motorcycles[1].title() + "."
print(message)

motorcycles[1] = 'Ns200'
motorcycles.append("ducati600") #To add
motorcycles.append("Toyota")

del motorcycles[-1]     #To remove.
del motorcycles[3]
motorcycles.remove("BMW")
print(motorcycles)

motorcycles.reverse()   #To reverse.
motorcycles.pop(0)
print(motorcycles)

len(motorcycles)  #To find the length of the list.

print(motorcycles[-2])
print(motorcycles[-1])


'''
    Summary:-
        Sieve of Eratosthenes. Create an array of n. Mark all numbers except 0 and 1 as True.
        We start off with a table of n numbers. Let's look at the first number, 2. We know all
        multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at
        the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ...
        must not be primes, so we mark them off as well. Now we look at the next number, 4,
        which was already marked off, so need to see for 4.

        4 is not a prime because it is divisible by 2, which means all multiples of 4 must also
        be divisible by 2 and were already marked off. So we can skip 4 immediately and go to
        the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20,
        5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need
        to start from 5 × 2 = 10.

        In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was
        already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by
        multiple of 3. Therefore, if the current number is p, we can always mark off multiples
        of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ...

        The terminating loop condition can be p < √n, as all non-primes ≥ √n must have already
        been marked off. When the loop terminates, all the numbers in the table that are non-
        marked are prime.

        The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n
        log log n).

        Using Multiple while or for loops in python still leads to a Time Limit Exceeded so,
        list comprehension is used which is implemented faster in python.

'''
class Solution:
    def countPrimes(self, n: int) -> int:

        if n == 0 or n == 1:
            return 0

        prime = [True for i in range(n)]
        prime[1] = prime[0] = False

        for i in range(2, int(n**0.5) + 1):
            if prime[i]:
                prime[i*i: n: i] = [False] * len(prime[i*i: n: i])

        return sum(prime)


from django.shortcuts import render, redirect
from django.http import HttpRequest, HttpResponse
from .models import LongToShort
from .models import ShortUrlDetails
# Create your views here.

def hello_world(request):
    return HttpResponse("Hello World!")

def home_page(request):

    context={
        'submitted':False,
        'error':False
    }

    if request.method=='POST':
        data = request.POST
        print("LONG URL:",data['longurl'])
        print("CUSTOM URL:",data['custom_name'])

        # CREATE
        try:
            obj = LongToShort(long_url= data['longurl'], short_url = data['custom_name'])
            obj.save()

            # READ
            context['date']=obj.date
            context['clicks']=obj.clicks
            context['submitted']=True
            context['longurl']=data['longurl']
            context['custom_name']=request.build_absolute_uri() + data['custom_name']
        except:
            context['error']=True
    else:
        print('USER SENT A GET REQUEST')

    return render(request,"index.html",context)

def redirect_url(request,shorturl):
    row = LongToShort.objects.filter(short_url=shorturl)
    if len(row)==0:
        return HttpResponse('No such short url exist')
    obj = row[0]
    long_url = obj.long_url
    obj.clicks += 1
    obj.save()
    print(long_url)
    return redirect(long_url)

def all_links(request):
    rows = LongToShort.objects.all()
    context = {'rows':rows}
    return render(request,'all-links.html',context)

def task(request):
    context = {'my_name':'Ambarish','x':10}
    return render(request,'task.html',context)


import math, copy
import numpy as np
import random

class Normal_distribution_likelihood:

    def __init__(self):
        self.xl = 0
        self.xr = 0
        self.ave = 0
        self.disp = 0

    def likelihood(self, xl,xr,ave,disp):
        self.xl = xl
        self.xr = xr
        self.ave = ave
        self.disp = disp

        pre_llist = []

        for i in range(0,6):
            total = (xl-ave[i*2])**2+(xr-ave[(i*2)+1])**2
            log_l_cal = -2*math.log(math.sqrt(disp[i]))-total/2/(disp[i])
            l_cal = math.exp(log_l_cal)
            pre_llist.append(l_cal)
        return pre_llist

        #pre_llist.sort()
        #return likelihood


"""
Created on Mon Nov 30 18:50:00 2020 (1399/9/10)
@author: Bahar Kaviani
description: Global information about all users
"""
import socket
import threading
import user as user

### global variables
# list of all connected IPs with their usernames
allUsers = []

"""
Defined on Thu Dec 3 18:06:00 2020 (1399/9/13)
description: add all users from users.txt to allUsers set
"""
def initializeAllUsers():
    # read from file and then close the file
    with open("users.txt", "r") as usersFile:
        for line in usersFile:
            # # extra print for checking
            # print("[users.txtfile]: " + line)
            IP, port, username = line.split(":")
            x = user.User(IP, port, username)
            allUsers.append(x)

"""
Defined on Fri Dec 4 11:56:00 2020 (1399/9/14)
description: add new user to allUsers set
"""
def addUser(IP, port, username):
    x = user.User(IP, port, username)

    with open("users.txt", "a") as usersFile:
        usersFile.write(x.IP + ":" + str(x.port) + ":"+ x.username)
        usersFile.write("\n")

    allUsers.append(x)


import os, pickle, time, urllib
import http.client
from urllib.parse import urlparse

from templater import additional_urls

do_check_links = True

link_exceptions = set([
    'https://uk.linkedin.com/in/jean-hugues-lestang-90b70073', # LinkedIn doesn't like links... in...?
    'https://uk.linkedin.com/in/greta-horvathova-5a22961b1',
    ])

if os.path.exists('last_checked_links.pkl'):
    last_checked_links = pickle.load(open('last_checked_links.pkl', 'rb'))
else:
    last_checked_links = {}

today = time.strftime('%d/%m/%Y')
last_checked_links = dict((url, day) for url, day in last_checked_links.items() if day==today)
last_updated = time.strftime('%Y/%m/%d')

def check_link(url, msg):
    if url in last_checked_links or url in link_exceptions:
        return
    # first try just getting the header (quick)
    p = urlparse(url)
    conn = http.client.HTTPConnection(p.netloc)
    try:
        conn.request('HEAD', p.path)
        resp = conn.getresponse()
    except Exception as ex:
        print('Failed: {msg}, URL {url}, exception {ex}'.format(msg=msg, url=url, ex=ex))
        return
    if resp.status >= 400:
        try:
            # Pretend we are a browser because some journals refuse connections otherwise
            urllib.request.urlopen(urllib.request.Request(url, headers={ 'User-Agent': 'Mozilla/5.0' }))
            last_checked_links[url] = today
        except Exception as ex:
            try:
                if hasattr(ex, 'getcode') and ex.getcode()==500: # just do a retry in this situation (internal server error)
                    ex.read()
                else:
                    raise
            except Exception as ex:
                print('Failed: {msg}, URL {url}, exception {ex}'.format(msg=msg, url=url, ex=ex))
    else:
        last_checked_links[url] = today

def check_links():

    if do_check_links:

        # # Check publication URLs are OK
        # for publication in papers.values():
        #     for _, url in publication.urls:
        #         check_link(url, "publication "+publication.name)

        # Check all additions links are OK
        for url, pagename in additional_urls:
            check_link(url, "page "+pagename)

    pickle.dump(last_checked_links, open('last_checked_links.pkl', 'wb'))


import os, sys
import numpy as np
import paddle
# paddle.enable_static()
import paddle.fluid as fluid
from paddle import ParamAttr
import paddle.nn as nn
import paddle.nn.functional as F
from collections import OrderedDict
import torch

SEED = 666
INPUT_SIZE = 89
KERNEL_SIZE = 1
STRIDES = (1,1)
PADDING = 0

def get_para_bias_attr(l2_decay, k, name):
    import math
    regularizer = paddle.regularizer.L2Decay(l2_decay)
    stdv = 1.0 / math.sqrt(k * 1.0)
    initializer = nn.initializer.Uniform(-stdv, stdv)
    weight_attr = ParamAttr(
        regularizer=regularizer, initializer=initializer, name=name + "_w_attr")
    bias_attr = ParamAttr(
        regularizer=regularizer, initializer=initializer, name=name + "_b_attr")
    return [weight_attr, bias_attr]

def paddle_lstm():
    np.random.seed(SEED)
    x = np.random.rand(1, 80, 512).astype(np.float32)
    # np.save('org.npy', x)
    with fluid.dygraph.guard():
        lstm = nn.LSTM(512, 256, num_layers=2, direction='bidirectional')

        # sd = np.load('lstm.npy', allow_pickle=True).tolist()
        # lstm.set_state_dict(sd)

        state_dict = lstm.state_dict()
        sd = OrderedDict()
        for key, value in state_dict.items():
            v = value.numpy()
            print(key, value.shape, np.sum(v), np.mean(v), np.max(v), np.min(v))
            sd[key] = v

        np.save('lstm.npy', sd)

        inp = fluid.dygraph.to_variable(x)
        ret, _ = lstm(inp)
        print(len(ret))
    return ret.numpy()

def torch_lstm():
    np.random.seed(SEED)
    org = torch.Tensor(np.random.rand(1, 80, 512).astype(np.float32))
    lstm = torch.nn.LSTM(512, 256, num_layers=2, batch_first=True, bidirectional=True)
    sd = np.load('lstm.npy', allow_pickle=True)
    sd = sd.tolist()

    for key, value in lstm.state_dict().items():
        lstm.state_dict()[key].copy_(torch.Tensor(sd[key]))

    ret, _ = lstm(org)
    return ret.data.numpy()

def torch_lstm_m():
    class EncoderWithRNN(torch.nn.Module):
        def __init__(self, in_channels, hidden_size):
            super(EncoderWithRNN, self).__init__()
            self.out_channels = hidden_size * 2
            self.rnn1 = torch.nn.LSTM(in_channels, hidden_size, bidirectional=False, batch_first=True, num_layers=2)
            self.rnn2 = torch.nn.LSTM(in_channels, hidden_size, bidirectional=False, batch_first=True, num_layers=2)

        def forward(self, x):
            self.rnn1.flatten_parameters()
            self.rnn2.flatten_parameters()
            out1, h1 = self.rnn1(x)
            out2, h2 = self.rnn2(torch.flip(x, [1]))
            return torch.cat([out1, torch.flip(out2, [1])], 2)

    lstm = EncoderWithRNN(10, 3)
    for key, value in lstm.state_dict().items():
        print(key, value.shape)

if __name__ == '__main__':
    print('==========paddle=================')
    a = paddle_lstm()
    print(a.shape)
    print('a: ', np.sum(a), np.mean(a), np.max(a), np.min(a))
    print('===========pytorch================')
    b = torch_lstm()
    print(b.shape)
    print('b: ', np.sum(b), np.mean(b), np.max(b), np.min(b))
    # print('===========pytorch_m================')
    # torch_lstm_m()


# -*- coding: utf-8 -*-
"""
Created on Sun May  3 00:11:14 2020

@author: Nadim Mahmud
"""

import dataprocessingutility as dp

# Loading data
directory = "D:\Portable\Git reps\Project Facebook"
message_title = "message_1.json"

dataset = dp.open_json(directory,message_title)

# Seperating usrs message int two lists

incoming,response = dp.serparate_two_users_message(data = dataset)

# Fitting and using model

from wordmodel import WordModel as wd
wd.fit(incoming,response,1)
stored = wd.count_associativity()

print(wd.replay('mara kha', 10)[0])

x = wd.response

y = (stored['ki'])


class Solution:
    """
    @param n: the number of digit
    @return: the largest palindrome mod 1337
    """

    def largestPalindrome(self, n):
        # write your code here
        max_r = int('9' * n)
        min_r = 10 ** (n - 1) - 1
        palindromes = []
        for i in range(max_r, min_r, -1):
            if palindromes and max(palindromes) // i > max_r:
                break
            for j in range(max_r, min_r, -1):
                mul = i * j
                if self.isPalindrome(mul):
                    palindromes.append(mul)
                    break
        return max(palindromes) % 1337

    # faster way
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0 or (x != 0 and x % 10 == 0):
            return False
        half = 0
        while x > half:
            half = half * 10 + x % 10
            x //= 10
        return x == half or half / 10 == x

sol = Solution()
print(sol.isPalindrome(9009))
print(sol.largestPalindrome(5))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 16 18:43:27 2023

@author: ram
"""
inputs=input()
hnc=[eval(i) for i in inputs.split()]

h=hnc[0]    # Total # of hours
n=hnc[1]    # No. of shops
c=hnc[2]    # Carrying capacity in litres

dist=[]     # Distance of a shop i from starting point
cost=[]     # Price per litre at shop i

for i in range(0,n):
    inputs=input()
    input_arr=[eval(i) for i in inputs.split()]
    dist.append(input_arr[0])
    cost.append(input_arr[1])

# Testing
# h=400
# n=4
# c=200
# dist=[0,100,150,300]
# cost=[1000,1300,1200,1100]

maxcost=0
for i in range(0,n):
    maxcost = max(maxcost,cost[i])

maxcost=h*maxcost

# mincost=[]
# for i in range(0,n+1):
#     mincost.append([])
#     for j in range(0,c+1):
#         mincost[i].append(maxcost+1)

mincost=[ [maxcost for j in range(0,c+1)] for i in range(0,n+1) ]

for j in range(0,c+1):
    mincost[0][j]=j*cost[0]

for i in range(1,n):
    for j in range(0,c+1):
        if(j + dist[i] - dist[i - 1] <= c):
            mincost[i][j] = min(mincost[i - 1][j + (dist[i] - dist[i - 1])], mincost[i - 1][dist[i] - dist[i - 1]] + j * cost[i])
        else:
            mincost[i][j] = min(mincost[i][j], mincost[i - 1][dist[i] - dist[i - 1]] + j * cost[i])

        if j > 0:
            mincost[i][j] = min(mincost[i][j], mincost[i][j - 1] + cost[i])

print(mincost[n - 1][h - dist[n - 1]])


from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QPushButton, QFrame, QMessageBox

from compoment.atx2agent.core.common.logs.log_uru import Logger
from compoment.atx2agent.core.task.task_manage import TaskType
from ui.test.execTaskThread import TaskManagerThread
from ui.test.model.model import Task, TaskStatus

logger = Logger().get_logger
class TestTaskRunModule(QFrame):
    def __init__(self, case_manager_controller=None,device_manager_controller=None,task_type_controller=None,task_manager_table_controller=None,parent=None):
        super(TestTaskRunModule, self).__init__(parent)
        self.initUI()
        self.case_manager_controller = case_manager_controller
        self.device_manager_controller =device_manager_controller
        self.task_type_controller = task_type_controller
        self.task_manager_table_controller = task_manager_table_controller

    def initUI(self):
        ################ 执行任务操作 ###############
        self.testTaskRunLayout = QHBoxLayout()
        self.testTaskRunLayout.setAlignment(Qt.AlignBottom)
        self.setLayout(self.testTaskRunLayout)

        self.run_case_label = QLabel("操作")
        self.testTaskRunLayout.addWidget(self.run_case_label)

        self.task_button = QPushButton('添加任务')
        self.testTaskRunLayout.addWidget(self.task_button)
        self.task_button.clicked.connect(self.on_add_task)

        self.run_task_button = QPushButton('执行任务')
        self.testTaskRunLayout.addWidget(self.run_task_button)
        self.run_task_button.clicked.connect(self.on_run_task)

        self.cancel_task_button = QPushButton('取消任务')
        self.testTaskRunLayout.addWidget(self.cancel_task_button)
        self.cancel_task_button.clicked.connect(self.on_cancel_task)

    def on_add_task(self):
        cases=[]
        selected_cases = self.case_manager_controller.get_selected_cases()
        selected_devices = self.device_manager_controller.get_selected_devices()
        selected_task_type =self.task_type_controller.get_task_type()
        if not selected_cases:
            QMessageBox.warning(self, '警告', '请选择测试用例')
            return
        if not selected_devices:
            QMessageBox.warning(self, '警告', '请选择一个设备')
            return
        if selected_task_type==TaskType.NONE:
            QMessageBox.warning(self, '警告', '请选择一种任务类型')
            return
        if self.task_manager_table_controller.is_device_occupied(selected_devices):
            QMessageBox.warning(self, '警告', f'设备[{selected_devices[0].serialsName}]已经被占用了')
            return
        # todo 根据任务类型的不同，需要选择对应的用例, 如果不同则弹出提示框
        try:
            if selected_task_type == TaskType.KW_UI_TEST:
                cases = self.case_manager_controller.get_test_case_list_view()
            elif selected_task_type == TaskType.PO_UI_TEST:
                cases = self.case_manager_controller.get_po_py_case_list()
                cases = sum(cases, [])
            if cases:
                # 根据设备的数量，创建多个任务
                for device in selected_devices:
                    task = Task(task_id=len(self.task_manager_table_controller.task_list), task_name='task1', test_cases=cases, device=device,
                                task_type=selected_task_type, status=TaskStatus.PENDING, result='',task_timeout=300)
                    self.task_manager_table_controller.add_task(task)
            else:
                QMessageBox.warning(self, '警告', '没有可执行的用例')
                return
        except Exception as e:
            logger.error("添加任务失败{}".format(e))
            QMessageBox.warning(self, '警告', '添加任务失败')

    def on_run_task(self):
        tasks =self.task_manager_table_controller.get_task_list()
        if tasks is None:
            QMessageBox.warning(self, '警告', '没有可以执行的任务')
            return
        if tasks:
            for task in tasks:   # 根据任务数量，创建多个线程
                # TODO 这里要判断一下有没有选中的任务
                if not self.task_manager_table_controller.no_selected_task_messagebox():
                    return
                # 如果任务已经在执行了，或者任务取消中，就不再执行
                # TODO 这里要改成通知 另一个专门做自动化用例执行的线程，去执行任务，而不是在这里直接执行，取消任务也是一样
                if task.status == TaskStatus.RUNNING or task.status == TaskStatus.CANCELLING:
                    QMessageBox.warning(self, '警告', '任务已经在执行了')
                    continue
                # 设置任务状态为执行中
                task.status = TaskStatus.RUNNING
                task_thread = TaskManagerThread(task)
                self.task_manager_table_controller.set_thread(task_thread)
                print("task_thread_id------------>:", id(task_thread))
                # task_thread.task_cancelled_signal.connect(self.task_manager.cancel_task)
                task_thread.update_status_signal.connect(self.task_manager_table_controller.update_task_status)
                task_thread.update_result_signal.connect(self.task_manager_table_controller.update_task_result)
                task_thread.start()

    def on_cancel_task(self):
        """
        取消任务
        @return:
        """
        # 获取选中的任务
        tasks = self.task_manager_table_controller.get_selected_task()
        print('取消任务: {}'.format(tasks))
        for task in tasks:
            print("任务类型：", type(task))
            self.task_manager_table_controller.cancel_task(task)


import logging
from flearn.client import Client
import math
import numpy as np
from flearn.fedave import Server as ServerBase

class Server(ServerBase):
    def __init__(self, data, model, parsed):
        logging.info('Using Federated avg to Train')
        self.data = data
        for key, val in parsed.items():
            logging.info("%s: %s" % (key, val))
            setattr(self, key, val)

        # initialize client
        self.clients = self.setup_clients(data, model)
        self.latest_model = None

    def update_local_model(self, client, learning_rates, betas):
        client.nesterov_grad_descent(self.num_epochs, self.batch_size, learning_rates, betas)

    def get_betas(self, rounds, num_epochs):
        # betas = [(rounds + i) / (rounds + i + 3) for i in range(num_epochs)]
        betas = [0.1] * num_epochs
        return betas

    def train(self, results_filename):
        # learning_rate = self.learning_rate
        if self.is_decay:
            learning_rates = self.get_epoch_learning_rates(0, self.learning_rate, self.lrconst, self.num_epochs)
        else:
            learning_rates = [self.learning_rate * self.lrconst] * self.num_epochs

        betas = self.get_betas(0, self.num_epochs)
        train_loss, test_loss = 0, 0
        final_iteration = 0
        is_break = False
        train_losss, test_losss, train_accs, test_accs = [], [], [], []
        num_selected_clients = max(int(self.partial_participation * len(self.clients)), 1)
        for i in range(self.num_rounds):
            final_iteration = i * self.num_epochs
            if i % self.eval_every == 0:
                train_loss, test_loss, train_acc, test_acc = self.evaluation()
                train_losss.append(train_loss); test_losss.append(test_loss)
                train_accs.append(train_acc); test_accs.append(test_acc)
                loginfostr = "Round {} Train_loss {}, Test_loss {}, " \
                             "Train_acc {}, Test_acc {}, lr {} beta {}".format(i,
                                                                               train_loss,
                                                                               test_loss,
                                                                               train_acc,
                                                                               test_acc,
                                                                               learning_rates[-1],
                                                                               betas[-1])
                logging.info(loginfostr)
                if train_loss < self.epsilon and self.model == 'linearregression':
                    logging.info("Final iterations {}".format(final_iteration))
                    is_break = True
                    break
                if train_acc > self.epsilon and self.model == 'logisticregression':
                    logging.info("Final iterations {}".format(final_iteration))
                    is_break = True
                    break
                if train_loss < self.epsilon and self.model == 'binarylogisticregression':
                    logging.info("Final iterations {}".format(final_iteration))
                    is_break = True
                    break
                if math.isnan(train_loss) or math.isinf(train_loss):
                    logging.info("Final iterations {}".format(1e8))
                    is_break = True
                    break

            if final_iteration > self.num_iterations:
                break

            active_clients = self.selected_clients(i,
                                                   num_selected_clients) if self.partial_participation != 1 else self.clients

            csolns = []  # buffer for receiving client solutions
            for client in active_clients:
                # client.set_params(self.latest_model)
                self.update_local_model(client, learning_rates, betas)
                csolns.append(client.get_params())
            self.latest_model = self.aggregate(csolns)
            self.sync_clients(self.latest_model)

            betas = self.get_betas(i, self.num_epochs)
            # warmup = 100
            if self.is_decay:
                learning_rates = self.get_epoch_learning_rates(i, self.learning_rate, self.lrconst, self.num_epochs)
                # learning_rate = 1/(i * self.learning_rate + self.lrconst)  # see ICLR'20 Xiang Li, C.5

            if (i * self.num_epochs) % 100 == 0:
                results = [train_losss, test_losss, train_accs, test_accs, final_iteration]
                np.save(results_filename, results)

        if is_break is False:
            logging.info("Final iterations {}".format(final_iteration))

        results = [train_losss, test_losss, train_accs, test_accs, final_iteration]
        np.save(results_filename, results)

        return results


from selenium import webdriver
import time
import math
from selenium.webdriver.chrome.options import Options

options = Options()
options.binary_location = "D:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"

def calc(number):
    return str(math.log(abs(12 * math.sin(int(number)))))

try:
    link = "http://suninjuly.github.io/redirect_accept.html"
    browser = webdriver.Chrome(options=options)
    browser.get(link)
    time.sleep(4)

    button = browser.find_element_by_class_name("trollface")
    button.click()

    new_window = browser.window_handles[1]
    browser.switch_to.window(new_window)
    time.sleep(1)

    x_element = browser.find_element_by_id("input_value")
    x = x_element.text

    y = calc(x)

    input = browser.find_element_by_id("answer")
    input.send_keys(y)

    button1 = browser.find_element_by_class_name("btn")
    button1.click()

finally:
    time.sleep(5)
    browser.quit()


class Ship:
    def __init__(self, x, y, horizontal, ship_type, length):
        """

        :param x: int
        :param y: int
        :param horizontal: int 0 or 1
        :param ship_type: bool
        :param length: int
        """
        self.bow = (x, y)
        self.horizontal = horizontal
        self.ship_type = ship_type
        self.length = length
        self.hit = [False] * length

    def render(self, x, y, mode=0):
        """
        This method for render ship demands of command (field_without_ships or field_with_ships) or standard
        :param x: int
        :param y: int
        :param mode: int
        :return: str
        """
        if not mode:  # Standard field render
            if self.ship_type:
                ind = x - self.bow[0] + y - self.bow[1]
                return "X" if self.hit[ind] else " "
            else:
                return "*" if self.hit[0] else " "
        elif mode == 1:  # Field with ships
            if self.ship_type:
                return "X"
            return "*" if self.hit[0] else " "
        else:  # Field without ships
            if not self.ship_type:
                return "*" if self.hit[0] else " "
            ind = x - self.bow[0] + y - self.bow[1]  # Index of wounded part of ship
            return "*" if self.hit[ind] else " "

    def shoot_at(self, coord):
        """
        This method takes coordinates of ship and makes it damaged and returns True if ship damaged
        :param coord:
        :return: bool
        """
        x, y = coord
        if self.ship_type:
            ind = x - self.bow[0] + y - self.bow[1]
            if not self.hit[ind]:
                self.hit[coord[0] - self.bow[0] + coord[1] - self.bow[1]] = True
                return True
        self.hit[0] = True
        return False


from apps.entity.models.agent import Agent
from apps.core.errors import AgentException
from apps.entity.repository.entity_repository import EntityRepository

class AgentRepository():

    @staticmethod
    def fetch_by_user(user):
        try:
            return Agent.objects.get(informations=user)
        except Agent.DoesNotExist:
            raise AgentException('unknown agent account', {'response_code': 'ERR', 'response_text': 'unknown agent'})

    @staticmethod
    def fetch_by_username(username):
        try:
            return Agent.objects.get(informations__username=username)
        except Agent.DoesNotExist:
            raise AgentException('unknown agent account', {'response_code': 'ERR', 'response_text': 'unknown agent'})

    @staticmethod
    def fetch_by_code(code):
        try:
            return Agent.objects.get(code=code)
        except Agent.DoesNotExist:
            raise AgentException('unknown agent account', {'response_code': 'ERR', 'response_text': 'unknown agent'})

    @staticmethod
    def to_json(code):
        try:
            agent = Agent.objects.get(code=code)
            data = {}
            data.update({'code': agent.code})
            data.update({'username': agent.informations.username})
            data.update({'first_name': agent.informations.first_name})
            data.update({'last_name': agent.informations.last_name})
            data.update({'entity': EntityRepository.to_json(code)})
            return data
        except Agent.DoesNotExist:
            raise AgentException('unknown agent account', {'response_code': 'ERR', 'response_text': 'unknown agent'})

    @staticmethod
    def get_batch_agent():
        return Agent.objects.get(informations__username='BATCH')


from dataclasses import dataclass, field
from typing import Optional
from nova.verbindung_tarifierbarkeits_request import VerbindungTarifierbarkeitsRequest

__NAMESPACE__ = "http://nova.voev.ch/services/v14/vertrieb"

@dataclass
class PruefenVerbindungTarifierbarkeits:
    class Meta:
        name = "pruefenVerbindungTarifierbarkeits"
        namespace = "http://nova.voev.ch/services/v14/vertrieb"

    verbindung_tarifierbarkeits_request: Optional[VerbindungTarifierbarkeitsRequest] = field(
        default=None,
        metadata={
            "name": "verbindungTarifierbarkeitsRequest",
            "type": "Element",
            "required": True,
        }
    )


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

# # model 5

# In[6]:

import polars as pl
import numpy as np
import pandas as pd

import tensorflow as tf

import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder

# import from the auxFunctions.py file
from auxFunctions import calculate_mae_and_mrrmse, mean_rowwise_rmse_loss, custom_mean_rowwise_rmse, create_model_checkpoint, plot_training_history

# ## pre-process data
# one-hot encode cell type
# <br>map sm_name to affinities_MPNN_CNN_BindingDB.csv

# In[7]:

de_train = pl.scan_parquet('de_train.parquet')
de_train_df = de_train.collect().to_pandas()

# test provided by kaggle --> upload predictions to kaggle to get the score
id_map = pd.read_csv('id_map.csv')

affinities = pd.read_csv('affinities_Transformer_CNN_BindingDB.csv', index_col=0)

# train dataset provided by kaggle
# - will be split into train/test/validation for internal testing before model is trained on the entire train and used to predict on the test in id_map

# In[8]:

def extractAffinities(sm_names, affinities):
    """
    Function to extract affinities from the affinities dataframe

    Parameters:
    - sm_names: List/Array of sm_names
    - affinities: Stored affinities predicted using DeepPurpose

    Returns:
    - Affinities as a numpy array
    """
    encoded_affinities = []
    for name in sm_names:
        filtered = affinities[affinities['sm_name'] == name]
        sm_affinities = filtered.iloc[:, 2:].values[0]
        encoded_affinities.append(sm_affinities)

    np_encoded_affinities = np.array(encoded_affinities)

    return np_encoded_affinities

# In[9]:

# one-hot encode cell_type
cell_type = de_train_df['cell_type'].to_numpy().reshape(-1, 1)
encoder = OneHotEncoder()
encoder.fit(cell_type)
# of type scipy.sparse._csr.csr_matrix
encoded_cell_type = encoder.transform(cell_type)

# map sm_name to affinities
sm_name = de_train_df['sm_name']

# has shape (614, 12766), of type numpy.ndarray
np_encoded_affinities = extractAffinities(sm_name, affinities)

# concatenate encoded_cell_type and np_encoded_affinities
# final shape (614, 12772)
encoded_features = np.hstack((encoded_cell_type.toarray(), np_encoded_affinities))

# wanted output
genes_lfc = de_train_df.drop(columns=['cell_type', 'sm_name', 'sm_lincs_id', 'SMILES', 'control'])

# In[10]:

# repeat for kaggle test set
kaggle_cell_type = id_map['cell_type'].to_numpy().reshape(-1, 1)
encoded_kaggle_cell_type = encoder.transform(kaggle_cell_type)

kaggle_sm_name = id_map['sm_name']
encoded_kaggle_affinities = extractAffinities(kaggle_sm_name, affinities)

# final shape (255, 12772)
encoded_kaggle_features = np.hstack((encoded_kaggle_cell_type.toarray(), encoded_kaggle_affinities))

# In[11]:

# Split the data into 70% training, 15% validation, and 15% testing
X_train, X_temp, y_train, y_temp = train_test_split(encoded_features, genes_lfc.values, test_size=0.3, shuffle=False)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, shuffle=False)

# used for final training before predicting on kaggle_test
full_features = encoded_features
full_labels = genes_lfc.values

# ## model training

# In[12]:

from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, Activation
from tensorflow.keras.models import Sequential

# In[ ]:

tf.random.set_seed(42)

model_2 = Sequential([
    Dense(3400, activation="tanh"),
    Dense(3000, activation="tanh"),
    Dense(2100, activation="tanh"),
    Dense(200, activation="tanh"),
    Dense(200, activation="tanh"),
    Dropout(0.2),
    Dense(18211, activation="linear")
])

model_2.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
                metrics=[custom_mean_rowwise_rmse])

history_2 = model_2.fit(X_train, y_train,
                       epochs=10,
                       validation_data=(X_val,y_val),
                       batch_size=32,
                       callbacks=[create_model_checkpoint("model_2", monitor="val_custom_mean_rowwise_rmse")])

calculate_mae_and_mrrmse(model=model_2, data=X_test, y_true=y_test)

# In[21]:

plot_training_history(history_2, metrics=["custom_mean_rowwise_rmse"])

kaggle_prediction = model_2.predict(encoded_kaggle_features, batch_size=1)

sample_submission = pd.read_csv('./sample_submission.csv')
sample_submission.iloc[:,1:] = kaggle_predictions

sample_submission.to_csv('submission_model_3.csv', index=False)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/3/18 16:44
# @Author : huangting
# @File : 014_max.py
# 获取最大值函数

# 以下实例中我们使用max()方法求最大值：

# author by : www.runoob.com

# 最简单的
print(max(1, 2))
print(max('a', 'b'))

# 也可以对列表和元组使用
print(max([1, 2]))
print(max((1, 2)))

# 更多实例
print("80, 100, 1000 最大值为: ", max(80, 100, 1000))
print("-20, 100, 400最大值为: ", max(-20, 100, 400))
print("-80, -20, -10最大值为: ", max(-80, -20, -10))
print("0, 100, -400最大值为:", max(0, 100, -400))
# 执行以上代码输出结果为：
# 2
# b
# 2
# 2
# 80, 100, 1000 最大值为: 1000
# -20, 100, 400 最大值为: 400
# -80, -20, -10 最大值为: -10
# 0, 100, -400 最大值为: 100

# 笔记
# 对比任意多个数字的大小
# 参考：
N = int(input('输入需要对比大小数字的个数：'))
print("请输入需要对比的数字：")
num = []
for i in range(1, N + 1):
    temp = int(input('输入第 %d 个数字' % i))
    num.append(temp)

print('您输入的数字为：', num)
print('最大值为：', max(num))

# 参考方法：
N = int(input('输入需要对比大小数字的个数：\n'))

num = [int(input('请输入第 %d 个对比数字 \n' % (i))) for i in range(1, N + 1)]

print('您输入的数字为:', list(num))
print('最大值为: ', max(num))

# 相比以上不用输入对比大小数字的个数:
a = []

while True:
    """输入q来结束输入数字"""
    try:
        a.append(int(input("输入数字: ")))
        break
    except ValueError:
        print("输入的不是数字")
while a[-1] != 'q':
    c = input("输入数字: ")
    if c != 'q':
        try:
            a.append(int(c))
        except ValueError:
            print("输入的不是数字")
    else:
        a.append(c)

del a[-1]

print("最大数字是", max(a))

# 感觉比楼上的稍微好理解一点：
# -*- coding UTF-8 -*-
# author by:Lebron
a = []
while True:
    # 输入q来结束输入数字
    c = input('请输入数字：')
    if c != 'q':
        try:
            i = int(c)
            a.append(i)
        except ValueError:
            print('输入的不是数字')
    else:
        break
print('最大数字是：', max(a))


#!/usr/bin/env python
# !-*-coding:utf-8 -*-
# !time :  10:48
# !@Author : Sweetbeaner
# !@File :.py
# !@Information :
# 练习: 利用递归函数实现求n这个数字的阶乘
def digui(num):
    if num >= 1:
        result = num * digui(num - 1)
    else:
        result = 1
    return result

print(digui(10))

def digui2(num):
    while num > 1:
        result = num * digui2(num - 1)
        return result
    result = 1
    return result
print(digui2(10))

8-01_用递归函数实现阶乘.py

8-01_用递归函数实现阶乘.py


storage = {}
while True:
    line = input().split(': ')
    if line[0] == 'statistics':
        break
    else:
        item = line[0]
        quantity = int(line[1])
        if item in storage:
            storage[item] += quantity
        else:
            storage[item] = quantity

print('Products in stock:')
for item in storage:
    print(f'- {item}: {storage[item]}')
print(f'Total Products: {len(storage)}')
print(f'Total Quantity: {sum(storage.values())}')


from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.http import HttpResponseForbidden
from books.models import Book
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test

SHOPPING_CART = "shopping_cart"

def group_required(arg_name):
    def decorator(view):
        def wrapper(request, *args, **kwargs):
            group_id = kwargs.get(arg_name)
            user = request.user
            if group_id in user.groups.values_list('id', flat=True):
                return view(request, *args, **kwargs)
            else:
                messages.error(request, "You are not a customer")
                return redirect(reverse('view_books_route'))
        return wrapper
    return decorator

# Create your views here.
@group_required('customer')
def add_to_cart(request, book_id):

    # if not request.user.groups.filter(name='customer').exists():
    #     messages.error(request, "You are not a customer")
    #     return redirect(reverse('view_books_route'))

    # open a file identified by the key 'shopping_cart' in the session (first argument)
    # if 'shopping_cart' is not found in the session, return an empty dictionary (second argument)
    cart = request.session.get(SHOPPING_CART, {})

    book = get_object_or_404(Book, pk=book_id)

    # CASE ONE: The book that the user is adding is not in the shopping cart yet
    if book_id not in cart:

        cart[book_id] = {
            'id': book_id,
            'title': book.title,
            'cost': float(book.cost),
            'qty': 1
        }
        messages.success(request, f"Book: {book.title} has been added to your cart")

    # CASE TWO: the book that the user is adding is ALREADY in the shopping cart
    else:
        cart[book_id]['qty'] += 1
        messages.success(request, f"One more book: {book.title} has been added to your cart")

    # REMEMEBR to save back to the session
    request.session[SHOPPING_CART] = cart

    return redirect(reverse('view_books_route'))

def view_cart(request):
    # retrieve the cart from the session
    cart = request.session.get(SHOPPING_CART)
    return render(request, 'cart/view_cart.template.html', {
        'cart': cart
    })

def remove_from_cart(request, book_id):
    cart = request.session.get(SHOPPING_CART)
    if book_id in cart:
        del cart[book_id]
        request.session[SHOPPING_CART] = cart
        messages.success(request, "Item has been removed")

    return redirect(reverse('view_cart_route'))

def update_quantity(request, book_id):
    cart = request.session.get(SHOPPING_CART)
    if book_id in cart:
        cart[book_id]['qty'] = request.POST['qty']  # eqv to Flask: request.form.get
        request.session[SHOPPING_CART] = cart
        messages.success(request, f"Quantity for {cart[book_id]['title']} has been changed")

    return redirect(reverse('view_cart_route'))


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

import io, os

from importerUtils import setDumpFolder, getDumpFolder, chooseImportStrategyAcis, STRATEGY_SAT, STRATEGY_STEP, STRATEGY_NATIVE
from importerSAT   import dumpSat, importModel, convertModel
from Acis          import setReader, AcisReader
from ezdxf         import readfile
from ezdxf.entities.acis import Solid3d

_3dSolids = []

def _getSatFileName(name):
	return  os.path.join(getDumpFolder(), "%s.sat" %(name))

def __is_binary__(entry):
	return hasattr(entry, 'sab') and len(getattr(entry, 'sab'))>0

def __is_text__(entry):
	return hasattr(entry, 'sat') and len(getattr(entry, 'sat'))>0

def __read_binary__(sab, name):
	global _3dSolids
	stream = io.BytesIO(sab)
	reader = AcisReader(stream)
	if (reader.readBinary()):
		reader.name = name
		_3dSolids.append(reader)

def __read_text__(sat, name):
	global _3dSolids
	stream = io.StringIO('\n'.join(sat))
	reader = AcisReader(stream)
	if (reader.readText()):
		reader.name = name
		_3dSolids.append(reader)

def read(filename):
	global _3dSolids

	_3dSolids = []
	name      = os.path.basename(os.path.splitext(filename)[0])
	i         = 0

	setDumpFolder(filename)
	doc = readfile(filename)
	for entry in doc.entities:
		if (__is_binary__(entry)):
			__read_binary__(entry.sab, '%s_%d' %(name, i))
			i += 1
		elif (__is_text__(entry)):
			__read_text__(entry.sat, '%s_%d' %(os.path.basename(os.path.splitext(filename)[0]), i))
			i += 1
	return True

def create3dModel(group, doc):
	global _3dSolids

	strategy = chooseImportStrategyAcis()
	for reader in _3dSolids:
		setReader(reader)
		if (strategy in (STRATEGY_SAT, STRATEGY_NATIVE)):
			importModel(group)
		elif (strategy == STRATEGY_STEP):
			convertModel(group, doc.Name)
		satFile = _getSatFileName(reader.name)
		if (not os.path.exists(satFile)):
			dumpSat(satFile, reader, False)
		setReader(None)
	return


import cv2
import numpy as np

# Función para determinar la forma de un contorno
def detect_shape(cnt):
    approx = cv2.approxPolyDP(cnt, 0.04 * cv2.arcLength(cnt, True), True)
    x, y, w, h = cv2.boundingRect(approx)
    aspect_ratio = float(w)/h
    if len(approx) == 3:
        return "Triangulo"
    elif len(approx) == 4:
        if aspect_ratio >= 0.95 and aspect_ratio <= 1.05:
            return "Cuadrado"
        else:
            return "Rectangulo"
    elif len(approx) == 5:
        return "Pentagono"
    elif len(approx) == 6:
        return "Hexagono"
    else:
        return "Circulo"

# Función para determinar el color predominante en un objeto
def detect_color(frame, cnt):
    mask = np.zeros(frame.shape[:2], np.uint8)
    cv2.drawContours(mask, [cnt], -1, 255, -1)
    hist = cv2.calcHist([frame], [0, 1, 2], mask, [8, 8, 8], [0, 256, 0, 256, 0, 256])
    color = hist.argmax()
    if color == 0:
        return "Rojo"
    elif color == 1:
        return "Verde"
    else:
        return "Azul"

# Inicializar la cámara
cap = cv2.VideoCapture(0)

while True:
    # Capturar un fotograma
    ret, frame = cap.read()

    # Convertir el fotograma a una imagen en escala de grises
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Aplicar el algoritmo Canny para detectar los bordes de los objetos
    edges = cv2.Canny(gray, 50, 150)

    # Encontrar los contornos de los objetos en la imagen de bordes
    contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Filtrar los contornos por área y perímetro
    contours = [cnt for cnt in contours if cv2.contourArea(cnt) > 100 and cv2.arcLength(cnt, True) > 100]

    # Dibujar los contornos y etiquetar
    for cnt in contours:
        shape = detect_shape(cnt)
        color = detect_color(frame, cnt)
        cv2.drawContours(frame, [cnt], 0, (0, 255, 0), 2)
        x, y, w, h = cv2.boundingRect(cnt)
        cv2.putText(frame, shape + " " + color, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

    # Mostrar la imagen resultante
    cv2.imshow("Reconocimiento de Figuras y Colores", frame)

    # Salir si se presiona la tecla 'q'
    if cv2.waitKey(1) == ord('q'):
        break

# Liberar los recursos
cap.release()
cv2.destroyAllWindows()


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

import sys

import PyQt5
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import uic

recommendUi = '../_uiFile/viewRecommend.ui'
from View.Main import MainDialog
class RecommendDialog(QDialog):

    def __init__(self,weather):
        QDialog.__init__(self, None)
        uic.loadUi(recommendUi, self)

        # 창
        self.setWindowIcon(QIcon("../image/hang_1.png"))
        self.setWindowTitle("recommend")

        self.r_img_clothes1.setStyleSheet('image:url(../image/hang.png);')
        self.r_img_clothes2.setStyleSheet('image:url(../image/hang_1.png);')
        self.r_img_clothes3.setStyleSheet('image:url(../image/hang_1.png);')

        self.r_btn_main.clicked.connect(self.click_main)
        self.r_btn_closet.clicked.connect(self.click_closet)
        self.img = ['', 'image:url(../image/cardigan.png);', 'image:url(../image/coat.png);','image:url(../image/fleece.png);', 'image:url(../image/hoodzip_up.png);'
            , 'image:url(../image/jacket.png);', 'image:url(../image/padding.png);']
        self.tems = ['','17℃~19℃', '12℃~16℃', '9℃~11℃', '5℃~8℃', '~4℃','','옷이없습니다',""]
        self.weather = weather
        self.clothes = ['-' for i in range(3)]
        self.names = ['-' for i in range(3)]
        self.weathers = ['-' for i in range(3)]
        self.temperatures = ['-' for i in range(3)]

        self.draw_ui()

    def draw_ui(self):
        #날씨, 온도
        from data.date import Date
        date = Date()

        temperature = int(self.weather.getTemperature())
        self.r_la_year.setText(str(date.getYear()))
        self.r_la_day.setText(date.__str__())
        self.r_la_tem.setText(str(temperature)+'℃')
        self.r_la_state.setText(self.weather.getComment())

        # 옷 추천
        f = open("../File/userClothesInfo.txt",'r',encoding='UTF-8')
        tem = 0
        if temperature>=20:
            tem = 7
        elif 17<=temperature<=19:
            tem = 1
        elif 12<=temperature<=16:
            tem = 2
        elif 9<=temperature<=11:
            tem = 3
        elif 5<=temperature<=8:
            tem = 4
        elif temperature<=4:
            tem = 5

        lines = f.readlines()
        i = 0
        for line in lines:
            line = line.split('/')
            if i<3: #3번
                if line[2] == self.tems[tem]:
                    self.names[i] = line[0]
                    self.weathers[i] = line[1]
                    self.temperatures[i] = line[2]
                    self.clothes[i] = line[3]
                    i += 1

        if i<3:
            for line in lines:
                line = line.split('/')
                if i < 3:  # 3번
                    if line[2] == self.tems[tem-1]:
                        self.names[i] = line[0]
                        self.weathers[i] = line[1]
                        self.temperatures[i] = line[2]
                        self.clothes[i] = line[3]
                        i += 1

                    elif line[2] == self.tems[tem+1]:
                        self.names[i] = line[0]
                        self.weathers[i] = line[1]
                        self.temperatures[i] = line[2]
                        self.clothes[i] = line[3]
                        i += 1

        #ui
        if self.names[0]!='-':
            self.r_img_clothes1.setStyleSheet(self.img[int(self.clothes[0])])
            self.r_la_clothes1_n.setText(self.names[0])
            self.r_la_clothes1_s.setText(self.weathers[0])
            self.r_la_clothes1_t.setText(self.temperatures[0])
        else:
            pass
            #예외

        if  self.names[1]!='-':
            self.r_img_clothes2.setStyleSheet(self.img[int(self.clothes[1])])
            self.r_la_clothes2_n.setText(self.names[1])
            self.r_la_clothes2_s.setText(self.weathers[1])
            self.r_la_clothes2_t.setText(self.temperatures[1])
        else:
            # self.r_img_clothes2.hide()
            self.r_la_clothes2_n.hide()
            self.r_la_clothes2_s.hide()
            self.r_la_clothes2_t.hide()

        if self.names[2] != '-':
            self.r_img_clothes3.setStyleSheet(self.img[int(self.clothes[2])])
            self.r_la_clothes3_n.setText(self.names[2])
            self.r_la_clothes3_s.setText(self.weathers[2])
            self.r_la_clothes3_t.setText(self.temperatures[2])
        else:
            # self.r_img_clothes3.hide()
            self.r_la_clothes3_n.hide()
            self.r_la_clothes3_s.hide()
            self.r_la_clothes3_t.hide()

    def click_main(self):

        self.accept()
        r = MainDialog()
        r.show()
        r.exec_()

    def click_closet(self):
        from View.Closet import ClosetDialog
        self.accept()
        r = ClosetDialog()
        r.show()
        r.exec_()

if __name__ == "__main__" :
    app = QApplication(sys.argv)
    weather = MainDialog.get_weather
    main_dialog = RecommendDialog(weather)
    main_dialog.show()
    # 프로그램을 이벤트루프로 진입시키는(프로그램을 작동시키는) 코드
    app.exec_()


'''*Gladiator Expenses

Input / Constraints

You will receive 5 parameters to your function:
First parameter – lost fights count – integer in the range [0, 1000].
Second parameter – helmet price - floating point number in range [0, 1000].
Third parameter – sword price - floating point number in range [0, 1000].
Fourth parameter – shield price - floating point number in range [0, 1000].
Fifth parameter – armor price - floating point number in range [0, 1000].

Every second lost game, his helmet is broken.
Every third lost game, his sword is broken.
When both his sword and helmet are broken in the same lost fight, his shield also brakes.
Every second time, when his shield brakes, his armor also needs to be repaired.

'''
lost_fights = int(input())
helmet_price = float (input())
sword_price = float (input())
shield_price = float (input())
armor_price = float (input())

expenses = 0

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

    if i % 2 == 0:
        expenses = expenses + helmet_price

    if i % 3 == 0:
        expenses = expenses + sword_price

    if (i % 3 == 0) and (i % 2 == 0):
        expenses = expenses + shield_price

    if i % 12 == 0 and i > 0:
        expenses = expenses + armor_price

print(f"Gladiator expenses: {expenses:.2f} aureus")


from bs4 import BeautifulSoup
from urllib.parse import urlparse
import re
import requests
import csv

nameList = []
urlList = []
busNameList = []
numberList = []
websiteBoolList = []
countyList = []

headers = {'User-Agent': 'Mozilla/5.1 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

def getDetails(content, url, county):
    global nameList
    global numberList
    global urlList
    global busNameList
    global websiteBoolList
    global countyList
    #Gets name of business
    try:
        nameStart = content.index('class="name">')
        name = content[nameStart:nameStart+100].split('>', 1)[-1]
        name = name.split("<", 1)[0]
    except:
        print("******** NAME NOT FOUND ********")
        name = "Not Found"

    if name not in nameList:
        nameList.append(name)
    else:
        return

    #Gets number of business
    try:
        numStart = content.index('"telephone">')
        number = content[numStart:numStart+100].split('>', 1)[-1]
        number = number.split("<", 1)[0]
    except:
        number = "Not Found"

    #Get website info
    webSiteTags = 0;
    webStart = ""
    try:
        webAttempt = content.index('class="contact-homepage')
        webSiteTags = 1;
        webStart = webAttempt
    except:
        pass
    if webSiteTags == 0:
        try:
            webAttempt = content.index('class="homepage icon"')
            webSiteTags = 1;
            webStart = webAttempt
        except:
            pass
    if webSiteTags == 0:
        try:
            webAttempt = content.index('class="visti_mysite"')
            webSiteTags = 1;
            webStart = webAttempt
        except:
            pass
    try:
        website = content[webStart:webStart+100].split('>', 1)[-1]
        websiteBool = "Yes"
    except:
        websiteBool = "No"

    print("***************************")
    print(url)
    print(": " + name)
    print(": " + number)
    print(": " + websiteBool)
    urlList.append(url)
    busNameList.append(name)
    numberList.append(number)
    websiteBoolList.append(websiteBool)
    countyList.append(county)

def searchPage(url):
    headers = {'User-Agent': 'Mozilla/5.1 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

    try:
        response = requests.get(url, headers=headers, timeout=15)
        content = str(response.content)
        response.close()
        #Checks if the business is in Dublin
        county = ""
        try:
            content.index('Dublin')
            isDublin = True
            county = "Dublin"
        except:
            isDublin = False
        #Checks if the business is in Kildare
        try:
            content.index('Kildare')
            isKildare = True
            county = "Kildare"
        except:
            isKildare = False
        #Checks if the business is in Meath
        try:
            content.index('Meath')
            isMeath = True
            county = "Meath"
        except:
            isMeath = False

        if (isDublin == True) or (isKildare == True) or (isMeath == True):
            getDetails(content, url, county)

    except Exception as e:
        print("error" + str(e))

try:
    letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    baseUrl = 'https://www.goldenpages.ie/business/sitemap/'
    for letter in letters:
        url = baseUrl + letter
        response = requests.get(url, headers=headers, timeout=15)
        content = str(response.content)
        response.close()
        soup = BeautifulSoup(content)
        #count = 0
        allLinks = soup.findAll('a')
        businessLinks = allLinks[26:]
        for link in businessLinks:
            li = link.get('href')
            #count = count + 1
            #if count > 3:
            #    break
            searchPage('https://www.goldenpages.ie' + li)

except Exception as e:
    print("error" + str(e))

with open('potential-clients.csv', 'w') as f:
    thewriter = csv.writer(f)
    num = len(urlList)
    for i in range(0,num):
        thewriter.writerow([urlList[i],busNameList[i],numberList[i],websiteBoolList[i],countyList[i]])


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 20:42:38 2021

@author: Juan Antonio

Title: Seguidor de movimiento

ver: 3.0
"""
# Librerias
import functions
import numpy as np
import cv2 as cv
import time
import matplotlib.pyplot as plt
"""
NOTA
----
functions se aplica en espacio base 480,640.
Si se usa una camara con diferentes dimensiones
se recomienda redimensionar con una mascara.

"""

# Variables
r = int(input('Radio: '))
pTime = 0
cTime = 0
datav = list()
print('--Press d to start--')
cap = cv.VideoCapture(0)
while True:
    n, frame = cap.read()
    cv.imshow('0', frame)
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

print('Recording inicial data')

n, frame = cap.read()
bframe = cv.medianBlur(frame,5)
gframe1 = cv.cvtColor(bframe, cv.COLOR_BGR2GRAY)
gframe1u, gframe1d = functions.division_up_down(gframe1)
gframe1uc = gframe1u.copy()
functions.profundidad(frame)
print('Launch')
sTime = time.time()
# Bucle
while True:
    # Funciones
    n, frame = cap.read()

    uf, df = functions.division_up_down(frame)

    umbralm, umbrald, framedif, gframe1= functions.movimiento(df, gframe1d)

    _, gframe1d = functions.division_up_down(gframe1)

    morph, blank, mascara, cannym, isTrue = functions.morphdata(umbralm, r)

    # up functions
    dif = functions.inclinacion(gframe1uc, frame)

    # Dilation-Shows
    if isTrue:
        mascarap, circ, cm, ci, cd, isTrue = functions.dilationdata(umbrald, mascara, r)
        if isTrue:
            functions.imshows(morph,blank,mascara,cannym,umbralm,umbrald,framedif, circ,mascarap, dif, gframe1u)
            Time = time.time()
            cTime = Time - pTime
            pTime = cTime
            stTime = Time - sTime
            datav = functions.data(datav,['T entre med',cTime],['Tiempo',stTime], ['circulo cords',cm[0]])
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

cap.release()
cv.destroyAllWindows()

# Data
x = list()
y = list()
for data in datav:
    x.append(data[2][1][0])
    y.append(480-data[2][1][1])
    for d in data:
        print(d)
graf = functions.graph(x, y)
graf.show()

print(x)
print(y)
print(len(datav))
print(stTime)


from datetime import datetime
from os import mkdir,getcwd,walk,remove,chmod,rmdir
from stat import S_IWUSR
from os.path import abspath,join
#from shutil import rmtree
from oneclick.discovery.sourceValidation import SourceValidation
from oneclick.config import Config
from cast_common.logger import Logger,INFO
from cast_common.util import create_folder

from pandas import Series,DataFrame

import re

#todo: review cleanup lists for aip and hl, do we need separate or can we keep it as one and run HL from AIP folder?

class cleanUpAIP(SourceValidation):

    def __init__(cls, config:Config, name = None, log_level:int=INFO):
        if name is None:
            name = cls.__class__.__name__
        super().__init__(config,cls.__class__.__name__,log_level)

    @property
    def cleanup_file_prefix(cls):
        return "AIP"

    def run(cls,config:Config):
        cls._log.debug('Source Code cleanup is in progress')

        output_path = abspath(f'{config.oneclick_work}/LOGS/{config.project_name}')
        create_folder(output_path)

        dir = config.base
        dateTimeObj=datetime.now()
        file_suffix=dateTimeObj.strftime("%d-%b-%Y(%H.%M.%S.%f)")

        exclusionFileList= abspath(f'{dir}\\scripts\\{cls.cleanup_file_prefix}deleteFileList.txt')
        with open(exclusionFileList) as f:
            files_list = f.read().splitlines()

        exclusionFolderList= abspath(f'{dir}\\scripts\\{cls.cleanup_file_prefix}deleteFolderList.txt')
        with open(exclusionFolderList) as f:
            folder_list = f.read().splitlines()

        apps= config.application
        cls._log.info(f'Running {cls.__class__.__name__} for all applications')
        found = True
        while found:
            found = False
            for app in apps:
                log_folder=f'{output_path}\\{app}'
                create_folder(log_folder)
                base = f'{log_folder}\\{cls.cleanup_file_prefix}'
                cleanup_log_file= f"{base}_deletedFiles_{file_suffix}.log"
                cls.cleanup_log = Logger('File',level=cls._log_level,file_name=cleanup_log_file,console_output=False)
                cls._log.info(f'Cleanup file log: {cleanup_log_file}')

                app_folder = abspath(f'{config.work}\\{cls.cleanup_file_prefix}\\{config.project_name}\\{app}')

                # cls._log.info(f'Reviewing {app} ({app_folder})')
                # with open (clean_up_log_file, 'a+') as file1:
                #     with open (clean_up_log_folder, 'a+') as file2:

                s=''
                folder_cnt=0
                file_cnt=0
                for subdir, dirs, files in walk(app_folder):
                        for dir in dirs:
                            if cls.find_with_list(dir,folder_list):
                                folder=join(subdir, dir)
                                rmtree(folder)
                                folder_cnt+=1
                                cls.cleanup_log.info(f'Folder: {folder}')

                        for file in files:
                            if cls.find_with_list(file,files_list):
                                file=join(subdir, file)
                                remove(file)
                                file_cnt+=1
                                cls.cleanup_log.info(f'Folder: {file}')

                cls._log.info(f'Removed {file_cnt} files and {folder_cnt} folders from {app_folder}')
        cls._log.debug('Source Code cleanup done')

    def find_with_list(cls,find_in:str,pattern:list):
        rslt = False
        for p in pattern:
            try:
                cls.cleanup_log.debug(f'matching: {p} in: {find_in}')
                if re.match(p,find_in):
                    rslt = True
                    break
            except re.error as ex:
                cls._log.warning(f'{ex.msg} for pattern {ex.pattern}')

        return rslt

def rmtree(top):
    for root, dirs, files in walk(top, topdown=False):
        for name in files:
            filename = join(root, name)
            chmod(filename, S_IWUSR)
            remove(filename)
        for name in dirs:
            rmdir(join(root, name))
    rmdir(top)

class cleanUpHL(cleanUpAIP):
    def __init__(cls,config:Config, log_level:int):
        super().__init__(config,cls.__class__.__name__,log_level)

    @property
    def cleanup_file_prefix(cls):
        return "HL"


A = [1,1,2,3,5,8,13,21,34,55,88]
B = [1,3,5,4,7,88,66,59,40,54]
C = []
for x in A:
	for s in B:
		if x == s:
			print(x)
			C.append(x)

print("List C sau khi luu tru cac so trung nhau ben list A,B: ",C)
for x in C:
	for s in B:
		if x == s:
			B.remove(s)
for x in C:
	for s in A:
		if x == s:
			A.remove(s)
print("List A sau khi xoa: ",A)
print("List B sau khi xoa: ",B)


# -*- coding: utf-8 -*-
# encoding:utf-8
import requests
import base64

request_url = {
    "通用文字识别": "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic",
    "数字识别": "https://aip.baidubce.com/rest/2.0/ocr/v1/numbers"
}

def get_access_token():
    headers = {
        b'Content-Type': 'application/json;charset=UTF-8'
    }
    params = {
        'client_id': 'xxx',
        'client_secret': 'xxx',
        'grant_type': 'xxx',
    }

    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    url = f'https://aip.baidubce.com/oauth/2.0/token'
    response = requests.post(url, params=params, headers=headers)
    if response:
        return response.json()

def get_img_str(urlName, imgfile):
    url = request_url.get(urlName)
    # 二进制方式打开图片文件
    f = open(imgfile, 'rb')
    img = base64.b64encode(f.read())

    params = {"image": img}
    access_token = get_access_token().get('access_token')
    url = url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data=params, headers=headers)
    if response:
        return response.json().get('words_result')


from collections import defaultdict
from functools import lru_cache
from typing import Tuple, Iterable, Dict, List, Set

import numpy as np

Vertex = int
EdgeList = Iterable[Tuple[Vertex, Vertex]]
AdjList = Dict[Vertex, List[Vertex]]

class DFGraph:
    def __init__(self, args: AdjList, v: Iterable[Vertex], vfwd_map: Dict[Vertex, Vertex], vloss: Vertex,
                 cost_cpu: Dict[Vertex, int] = None, cost_ram: Dict[Vertex, int] = None,
                 node_names: Dict[Vertex, str] = None, cost_ram_parameters: int = 0, key=""):
        """
        Graph defines the forward and backward graph for a neural network
        :param args (Dict[int, List[int]]): Dependency listing, where arguments ordered
        :param v: List of nodes in the graph
        :param vfwd_map: Mapping from forward graph to corresponding nodes in the reverse graph
        :param cost_cpu: Dictionary mapping nodes to respective integral runtime costs (for forward/backward operators)
        :param cost_ram: Dictionary mapping nodes to respective integral memory costs (for forward/backward operators)
        :param key: If set, will store property that allows cache persistence in some experiments
        """
        self.key = key
        self.args = defaultdict(list, args)
        self.v = list(sorted(v))
        self.size = len(self.v)
        self.edge_list = adj_to_edge_list(self.args, reverse_edge=True)
        self.vfwd_map = vfwd_map
        self.vfwd = list(sorted(vfwd_map.keys())) if vfwd_map else self.v
        self.vloss = vloss
        self.node_names = node_names if node_names is not None else {}
        if self.vloss not in self.node_names:
            self.node_names[self.vloss] = "Loss"
        self.size_fwd = len(self.vfwd)
        self.edge_list_fwd = self.induce_subgraph(self.vfwd)
        self.cost_cpu = cost_cpu if cost_cpu else {v: 1 for v in set(self.v + [self.vloss])}
        self.cost_ram = cost_ram if cost_ram else {v: 1 for v in set(self.v + [self.vloss])}
        self.cost_cpu_np = np.array([cost for _v, cost in sorted(self.cost_cpu.items())])
        self.cost_ram_np = np.array([ram for _v, ram in sorted(self.cost_ram.items())])
        self.cost_cpu_fwd = {v: cost_cpu[v] for v in self.vfwd} if cost_cpu else {v: 1 for v in self.vfwd}
        self.cost_ram_fwd = {v: cost_ram[v] for v in self.vfwd} if cost_ram else {v: 1 for v in self.vfwd}
        self.cost_ram_parameters = cost_ram_parameters

    @property
    def cost_ram_fixed(self):
        """Get fixed memory costs for the model (parameters and their gradients)"""
        return int(2 * self.cost_ram_parameters)

    def ram_gcd(self, *othervals):
        values = list(self.cost_ram.values())
        # vals.append(self.cost_ram_fixed)
        values.extend(othervals)
        values = np.array(values)
        intvalues = np.array(values, dtype=int)
        if not np.allclose(intvalues, values):  # GCD is 1 if values are not integral
            return 1
        return np.gcd.reduce(intvalues)

    def cpu_gcd(self, *othervals):
        values = list(self.cost_cpu.values())
        values.extend(othervals)
        values = np.array(values)
        intvalues = np.array(values, dtype=int)
        if not np.allclose(intvalues, values):  # GCD is 1 if values are not integral
            return 1
        return np.gcd.reduce(intvalues)

    @property
    @lru_cache(maxsize=None)
    def max_degree(self):
        counts = defaultdict(int)
        for (i, j) in self.edge_list:
            counts[j] += 1
            counts[i] += 1
        return max(counts.values())

    @property
    @lru_cache(maxsize=None)
    def checkpoint_set(self) -> Set[Vertex]:
        """Determine checkpointable nodes in a forward graph (not backward)"""

        def connected_components(V: Iterable[int], E: EdgeList):
            def dfs(graph, node, visited):
                if node not in visited:
                    visited.append(node)
                    for n in graph[node]:
                        dfs(graph, n, visited)
                return visited

            unvisited = set(V)
            adj_list = edge_to_adj_list(E, convert_undirected=True)
            components = 0
            while len(unvisited) > 0:
                v = unvisited.pop()
                visited = dfs(adj_list, v, [])
                for v in visited:
                    unvisited.discard(v)
                components += 1
            return components

        E = list(self.edge_list_fwd)
        V = set([i for (i, j) in E] + [j for (i, j) in E]).union({-1, -2})  # directed to undirected graph
        E = [(i, j) for (i, j) in E if i in V and j in V] + [(-1, 0), (max(V), -2)]

        checkpoint_ok = set()
        for v in filter(lambda v: v >= 0, V):  # ignore placeholders for input and output
            # count connected components in induced subgraph F = G / v
            Vprime = {x for x in V if x != v}
            Eprime = {e for e in E if v not in e}
            n_components = connected_components(Vprime, Eprime)
            if n_components > 1:
                checkpoint_ok.add(v)
        return checkpoint_ok

    @property
    def checkpoint_set_all(self) -> set:
        E = list(self.edge_list_fwd)
        V = set([i for (i, j) in E] + [j for (i, j) in E])
        return V

    @property
    @lru_cache(maxsize=None)
    def topological_order_fwd(self):
        E = self.edge_list_fwd

        def helper(adj_list_, v, visited_, stack_):
            visited_[v] = True
            for i in adj_list_[v]:
                if not visited_[i]:
                    helper(adj_list_, i, visited_, stack_)
            stack_.insert(0, v)

        adj_list = edge_to_adj_list(E, convert_undirected=True)
        num_nodes = len(adj_list.keys())

        visited = [False] * num_nodes
        stack = []
        for i in range(num_nodes):
            if not visited[i]:
                helper(adj_list, i, visited, stack)
        return stack

    @property
    @lru_cache(maxsize=None)
    def predecessor_dict(self):
        preds = defaultdict(list)
        for eidx, (u, v) in enumerate(self.edge_list):
            preds[v].append((eidx, u))
        return preds

    @property
    @lru_cache(maxsize=None)
    def successor_dict(self):
        sucs = defaultdict(list)
        for eidx, (u, v) in enumerate(self.edge_list):
            sucs[u].append((eidx, v))
        return sucs

    def predecessors(self, node) -> Set[Vertex]:
        return {u for (_, u) in self.predecessor_dict[node]}

    def successors(self, node) -> Set[Vertex]:
        return {u for (_, u) in self.successor_dict[node]}

    def predecessors_indexed(self, node):
        return self.predecessor_dict[node]

    def successors_indexed(self, node):
        return self.successor_dict[node]

    def induce_subgraph(self, nodes: List[int]):
        return [e for e in self.edge_list if all(map(lambda x: x in nodes, e))]

    def is_forward_node(self, node: int):
        return not self.is_loss_node(node) and node in self.vfwd

    def is_backward_node(self, node: int):
        return not self.is_loss_node(node) and not self.is_forward_node(node)

    def is_loss_node(self, node: int):
        return node == self.vloss

    def forward_to_backward(self, node: int):
        if self.is_loss_node(node):
            return None
        assert self.is_forward_node(node)
        return self.vfwd_map[node]

    @lru_cache(maxsize=None)
    def backward_to_forward(self, node: int):
        assert self.is_backward_node(node)
        return next(key for key, value in self.vfwd_map.items() if value == node)

    def dependency_order(self, node: int):
        return self.args[node]

    def max_degree_ram(self):
        """compute minimum memory needed for any single node (ie inputs and outputs)"""
        return max([sum([self.cost_ram[u] for u in self.predecessors(v)]) + self.cost_ram[v] for v in self.vfwd])

def gen_linear_graph(forward_node_count, **kwargs):
    """
    gen_linear_graph will generate linear-style graphs like VGG and AlexNet.
    Method returns forward and backward graphs. Pass cost_ram and cost_cpu as kwargs.
    :param forward_node_count: number of forward (not backward nodes)
    :return: Graph object containing linear graph
    """
    args = defaultdict(list)
    vfwd_map = {}
    loss_node_idx = forward_node_count
    for i in range(forward_node_count * 2):
        args[i + 1].append(i)
        if i < forward_node_count:
            corresponding_bwd = (forward_node_count * 2) - i
            args[corresponding_bwd].append(i)
            vfwd_map[i] = corresponding_bwd
    v = list(vfwd_map.keys()) + list(vfwd_map.values()) + [loss_node_idx]
    return DFGraph(args=args, v=v, vfwd_map=vfwd_map, vloss=loss_node_idx, **kwargs)

def edge_to_adj_list(E: EdgeList, convert_undirected=False):
    """Returns an (undirected / bidirectional) adjacency list"""
    adj_list = defaultdict(set)
    for (i, j) in list(E):
        adj_list[i].add(j)
        if convert_undirected:
            adj_list[j].add(i)
    return adj_list

def adj_to_edge_list(E: AdjList, convert_undirected=False, reverse_edge=False):
    """Returns an edge list
    :param E: AdjList -- input graph
    :param convert_undirected: bool -- if true, add u -> v and v -> u to output graph
    :param reverse_edge: bool -- if true, reverse edge direction prior to conversion
    :return:
    """
    edge_list = []
    for u, deps in E.items():
        for v in deps:
            edge = (u, v) if not reverse_edge else (v, u)
            edge_list.append(edge)
            if convert_undirected:
                edge_list.append(tuple(reversed(edge)))
    return edge_list