from ctypes import *
from Car import *
import csv
import sys
import time
import math
rs = CDLL('./IMU/rs232.so')
spatial = CDLL('./IMU/spatial_packets.so')
packets = CDLL('./IMU/an_packet_protocol.so')

######### defines & macros #################
AN_PACKET_HEADER_SIZE = 5
AN_MAXIMUM_PACKET_SIZE =  255
AN_DECODE_BUFFER_SIZE = 10*(AN_MAXIMUM_PACKET_SIZE+AN_PACKET_HEADER_SIZE)
RADIANS_TO_DEGREES = 180.0/math.pi
accelerometer_range_4g = 1
gyroscope_range_500dps = 1
magnetometer_range_2g = 0
MAXIMUM_PACKET_PERIODS = 50
packet_id_utm_position = 34
packet_id_system_state = 20
packet_id_unix_time = 21

########## structs ##########################
class an_packet_t(Structure):
    _fields_ = [("id", c_uint8),
                ("length", c_uint8),
                ("header", c_uint8*AN_PACKET_HEADER_SIZE),
                ("data", c_void_p)]

class an_decoder_t(Structure):
    _fields_ = [("buffer", c_uint8 * AN_DECODE_BUFFER_SIZE),
                ("buffer_length", c_uint16),
                ("crc_errors", c_uint)]

class sensor_ranges_packet_t(Structure):
	_fields_ = [("permanent",c_uint8),
                ("accelerometers_range",c_uint8),
                ("gyroscopes_range", c_uint8),
                ("magnetometers_range",c_uint8)]

class utm_position_packet_t(Structure):
	_fields_ = [("position",c_double*3),
                ("zone",c_char)]

class packet_period_t(Structure):
    _fields_ = [('packet_id',c_uint8),
                ('period',c_uint32)]

class packet_periods_packet_t(Structure):
    _fields_ = [('permanent',c_uint8),
                ('clear_existing_packets',c_uint8),
                ('packet_periods', packet_period_t*MAXIMUM_PACKET_PERIODS)]

class unix_time_packet_t(Structure):
    _fields_ = [('unix_time_seconds',c_uint32),
                ('microseconds',c_uint32)]

# class b(Structure):
# 			unsigned int orientation_filter_initialised :1; 1
# 			unsigned int ins_filter_initialised :1;2
# 			unsigned int heading_initialised :1;3
# 			unsigned int utc_time_initialised :1;4
# 			unsigned int gnss_fix_type :3;5,6,7
# 			unsigned int event1_flag :1;8
# 			unsigned int event2_flag :1;9
# 			unsigned int internal_gnss_enabled :1;10
# 			unsigned int magnetic_heading_enabled :1;11
# 			unsigned int velocity_heading_enabled :1;12
# 			unsigned int atmospheric_altitude_enabled :1;13
# 			unsigned int external_position_active :1;14
# 			unsigned int external_velocity_active :1;15
# 			unsigned int external_heading_active :1;16

class system_state_packet_t(Structure):
    _fields_ = [("system_status",c_uint16),
                ("filter_status",c_uint16),
                ("unix_time_seconds", c_uint32),
                ("microseconds", c_uint32),
                ("latitude", c_double),
                ("longitude",c_double),
                ("height",c_double),
                ("velocity",3*c_float),
                ("body_acceleration",3*c_float),
                ("g_force",c_float),
                ("orientation",3*c_float),
                ("angular_velocity",3*c_float),
                ("standard_deviation",3*c_float)]

packets.an_packet_decode.restype = POINTER(an_packet_t)
spatial.encode_sensor_ranges_packet.restype = POINTER(an_packet_t)
spatial.encode_packet_periods_packet.restype = POINTER(an_packet_t)
# spatial.decode_utm_position_packet.restype = c_int

############# costants %%%%%%%%%%%%%%%%%%%%%%%%
comPort = "COM3"
# comPort = "/dev/ttyUSB0" #nvidia's comport

########### auxilary functions #############

def  an_packet_transmit(an_packet):
    packets.an_packet_encode(byref(an_packet))
    return rs.SendBuf(packets.an_packet_pointer(byref(an_packet)), packets.an_packet_size(byref(an_packet)))

def set_sensor_ranges():

	sensor_ranges_packet = sensor_ranges_packet_t()
	sensor_ranges_packet.permanent = True
	sensor_ranges_packet.accelerometers_range = accelerometer_range_4g
	sensor_ranges_packet.gyroscopes_range = gyroscope_range_500dps
	sensor_ranges_packet.magnetometers_range = magnetometer_range_2g

	an_packet = spatial.encode_sensor_ranges_packet(byref(sensor_ranges_packet))
	an_packet_transmit(an_packet)

	# an_packet_free(&an_packet)

def set_utm_packet_rate():
    utm_rate_packet = packet_periods_packet_t()
    utm_rate_packet.clear_existing_packets = 0
    utm_rate_packet.packet_periods[0].packet_id = packet_id_utm_position
    utm_rate_packet.packet_periods[0].period = 1

    an_packet = spatial.encode_packet_periods_packet(byref(utm_rate_packet))
    an_packet_transmit(an_packet)

    # an_packet_free(&an_packet)

########### main functions ################
def ImuLoop(q, plottingFileName, trackMap):
    an_decoder = an_decoder_t()
    an_packet = an_packet_t()
    system_state_packet = system_state_packet_t()
    utm_position_packet = utm_position_packet_t()
    unix_time_packet = unix_time_packet_t()

    if(rs.OpenComport(create_string_buffer(comPort.encode('utf-8')),115200)==0):
        print('opend comport sucssesfuly')

    else:
        print ('faile to open comport')
        # exit(0)

    packets.an_decoder_initialise(byref(an_decoder))

    ############# Get a GPS FIX ###############
    ############# To Do: this funtion still dosent work problam is filter_status alwaya = 0 #################
    # No_fix = True
    # while No_fix == True:
    #     pointer = packets.an_decoder_pointer(byref(an_decoder))
    #     size = packets.an_decoder_size(byref(an_decoder))
    #     bytes_received = rs.PollComport(pointer,size)
    #     if bytes_received>0:
    #         packets.an_decoder_increment(byref(an_decoder),bytes_received)

    #         an_packet = packets.an_packet_decode(byref(an_decoder))
    #         while an_packet:
    #             if an_packet.contents.id == packet_id_system_state:
    #                 res = spatial.decode_system_state_packet(byref(system_state_packet),an_packet)
    #                 if(res == 0):
    #                     #printf("No fix yet:\n");
    #                     if system_state_packet.filter_status !=0:
    #                         print ('someting in filter status')
    #                     # if system_state_packet.filter_status & 112 == 32:
    #                     #     No_fix = False
    #                     #     print("GNSS FIX STATUS: %d\n", system_state_packet.filter_status.b.gnss_fix_type)
    #                     # an_packet_free(&an_packet)
    #             an_packet = packets.an_pac

    null_ptr = POINTER(c_int)()
        # set_utm_packet_rate()
    while 1:
        pointer = packets.an_decoder_pointer(byref(an_decoder))
        size = packets.an_decoder_size(byref(an_decoder))
        bytes_received = rs.PollComport(pointer,size)
        if bytes_received>0:
            packets.an_decoder_increment(byref(an_decoder),bytes_received)
            an_packet = packets.an_packet_decode(byref(an_decoder))

            if an_packet:
                id = an_packet.contents.id
                if id == 20 :
                    res = spatial.decode_system_state_packet(byref(system_state_packet),an_packet)
                    if(res == 0):
                        # print("Roll = {0}, Pitch = {1}, Heading = {2}\n".format(system_state_packet.orientation[0] * RADIANS_TO_DEGREES, system_state_packet.orientation[1] * RADIANS_TO_DEGREES, system_state_packet.orientation[2] * RADIANS_TO_DEGREES))
                        # q.put("Roll = {0}, Pitch = {1}, Heading = {2}\n".format(system_state_packet.orientation[0] * RADIANS_TO_DEGREES, system_state_packet.orientation[1] * RADIANS_TO_DEGREES, system_state_packet.orientation[2] * RADIANS_TO_DEGREES))
                        q.put(CarStatus(heading = system_state_packet.orientation[2] * RADIANS_TO_DEGREES ,uptadeType = 2))
                elif id == packet_id_utm_position:
                    res = spatial.decode_utm_position_packet(byref(utm_position_packet),an_packet)
                    if(res == 0):

                        x = utm_position_packet.position[0]
                        y = utm_position_packet.position[1]
                        z = utm_position_packet.position[2]
                        q.put(CarStatus(x,y,z,uptadeType = 1))

                elif id == packet_id_unix_time:
                    res = spatial.decode_unix_time_packet(byref(unix_time_packet),an_packet)
                    if(res == 0):
                        # print( unix_time_packet.unix_time_seconds)
                        q.put(CarStatus(unixTime = unix_time_packet.unix_time_seconds, microSeconds =  unix_time_packet.microseconds,uptadeType = 4))

    rs.CloseComport()


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

""" Constant values for NNGT """

import sys
from types import ModuleType

import scipy as sp
import scipy.sparse as ssp

#-----------------------------------------------------------------------------#
# All and version
#------------------------
#

__all__ = [
    "version",
    "glib_data",
    "glib_func",
    "default_neuron",
    "default_synapse",
    "POS",
    "DIST"
    "WEIGHT",
    "DELAY",
    "TYPE",
    "use_library"
]

version = '0.4'
''' :class:`string`, the current version '''

#-----------------------------------------------------------------------------#
# Graph libraries
#------------------------
#

# name, lib and Graph object
glib_data = {
    "name": "",
    "library": None,
    "graph": object
}

# store the main functions
glib_func = {
    "adjacency": None,
    "assortativity": None,
    "betweenness": None,
    "clustering": None,
    "components": None,
    "diameter": None,
    "reciprocity": None
}

# switch libraries
def use_library(library, reloading=True):
    '''
    Allows the user to switch to a specific graph library.

    .. warning:
        If :class:`~nngt.Graph` objects have already been created, they will no
        longer be compatible with NNGT methods.

    Parameters
    ----------
    library : string
        Name of a graph library among 'graph_tool', 'igraph', 'networkx'.
    reloading : bool, optional (default: True)
        Whether the graph objects should be reloaded (this should always be set
        to True except when NNGT is first initiated!)
    '''

    if library == "graph_tool":
        # library and graph object
        import graph_tool as glib
        from graph_tool import Graph as GraphLib
        glib_data["name"] = "graph_tool"
        glib_data["library"] = glib
        glib_data["graph"] = GraphLib
        # analysis functions
        from graph_tool.spectral import adjacency as _adj
        from graph_tool.centrality import betweenness
        from graph_tool.correlations import assortativity as assort
        from graph_tool.topology import (edge_reciprocity,
                                        label_components, pseudo_diameter)
        from graph_tool.clustering import global_clustering
        glib_func["assortativity"] = assort
        glib_func["betweenness"] = betweenness
        glib_func["clustering"] = global_clustering
        glib_func["scc"] = label_components
        glib_func["wcc"] = label_components
        glib_func["diameter"] = pseudo_diameter
        glib_func["reciprocity"] = edge_reciprocity
        # defining the adjacency function
        def adj_mat(graph, weights=None):
            if weights is not None:
                weights = graph.edge_properties[weights]
            return _adj(graph, weights).T
    elif library == "igraph":
        # library and graph object
        import igraph as glib
        from igraph import Graph as GraphLib
        glib_data["name"] = "igraph"
        glib_data["library"] = glib
        glib_data["graph"] = GraphLib
        # functions
        glib_func["assortativity"] = None
        glib_func["nbetweenness"] = None
        glib_func["ebetweenness"] = None
        glib_func["clustering"] = None
        glib_func["scc"] = None
        glib_func["wcc"] = None
        glib_func["diameter"] = None
        glib_func["reciprocity"] = None
        # defining the adjacency function
        def adj_mat(graph, weights=None):
            n = graph.node_nb()
            if graph.edge_nb():
                xs, ys = map(sp.array, zip(*graph.get_edgelist()))
                if not graph.is_directed():
                    xs, ys = sp.hstack((xs, ys)).T, sp.hstack((ys, xs)).T
                else:
                    xs, ys = xs.T, ys.T
                data = sp.ones(xs.shape)
                if weights is not None:
                    data = weights
                    if not graph.is_directed():
                        data.extend(data)
                coo_adj = ssp.coo_matrix((data, (xs, ys)))
                return coo_adj.tocsr()
            else:
                return ssp.csr_matrix((n,n))
    elif library == "networkx":
        # library and graph object
        import networkx as glib
        from networkx import DiGraph as GraphLib
        glib_data["name"] = "networkx"
        glib_data["library"] = glib
        glib_data["graph"] = GraphLib
        # functions
        from networkx.algorithms import ( diameter,
            strongly_connected_components, weakly_connected_components,
            degree_assortativity_coefficient )
        def overall_reciprocity(g):
            num_edges = g.number_of_edges()
            num_recip = (num_edges - g.to_undirected().number_of_edges()) * 2
            if n_all_edge == 0:
                raise ArgumentError("Not defined for empty graphs")
            else:
                return num_recip/float(num_edges)
        nx_version = glib.__version__
        v_major, v_minor = nx_version.split('.')
        if int(v_major) > 1 or int(v_minor) > 10:
            from networkx.algorithms import overall_reciprocity
        glib_func["assortativity"] = degree_assortativity_coefficient
        glib_func["diameter"] = diameter
        glib_func["reciprocity"] = overall_reciprocity
        glib_func["scc"] = strongly_connected_components
        glib_func["wcc"] = diameter
        # defining the adjacency function
        from networkx import to_scipy_sparse_matrix as adj_mat
    glib_func["adjacency"] = adj_mat
    if reloading:
        reload(sys.modules["nngt"].core.graph_objects)
        reload(sys.modules["nngt"].core)
        reload(sys.modules["nngt"].analysis)
        reload(sys.modules["nngt"].analysis.gt_analysis)
        reload(sys.modules["nngt"].generation)
        reload(sys.modules["nngt"].generation.graph_connectivity)
        reload(sys.modules["nngt"].plot)
        reload(sys.modules["nngt"].lib) #@todo: make price algo and remove this
        reload(sys.modules["nngt"].core.graph_classes)
        from nngt.core.graph_classes import (Graph, SpatialGraph, Network,
                                             SpatialNetwork)
        sys.modules["nngt"].Graph = Graph
        sys.modules["nngt"].SpatialGraph = SpatialGraph
        sys.modules["nngt"].Network = Network
        sys.modules["nngt"].SpatialNetwork = SpatialNetwork

# import the graph libraries the first time
try:
    use_library("graph_tool", False)
except:
    try:
        use_library("igraph", False)
    except:
        try:
            use_library("networkx", False)
        except:
            raise ImportError( "This module needs one of the following graph \
libraries to work:  `graph_tool`, `igraph`, or `networkx`.")

#-----------------------------------------------------------------------------#
# Names
#------------------------
#

POS = "position"
DIST = "distance"
WEIGHT = "weight"
BWEIGHT = "bweight"
DELAY = "delay"
TYPE = "type"

#-----------------------------------------------------------------------------#
# Basic values
#------------------------
#

#~ default_neuron = "iaf_neuron"
default_neuron = "aeif_cond_alpha"
''' :class:`string`, the default NEST neuron model '''
default_synapse = "static_synapse"
''' :class:`string`, the default NEST synaptic model '''
default_delay = 1.
''' :class:`double`, the default synaptic delay in NEST '''


# a code to read a file contains words and numbers
# extract all numbers .. compute the sum of them
import re

h = open('sample.txt')
file = h.read()

numbers = []
newNumbers = []
result = 0

for line in file :
	numbers = re.findall('[0-9]+',file)  # items is str

for i in numbers :
	newNumbers.append(int(i)) # create a new list of integers

for i in newNumbers :
	result += i
print(result)


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

from unittest import TestCase
from unittest.mock import MagicMock, patch

import numpy as np
from copulas.univariate import Univariate
from sklearn.gaussian_process import GaussianProcessRegressor

from btb.tuning.metamodels.gaussian_process import (
    GaussianCopulaProcessMetaModel, GaussianProcessMetaModel)

class TestGaussianProcessMetaModel(TestCase):

    def test___init__(self):
        # run
        instance = GaussianProcessMetaModel()

        # assert
        assert instance._MODEL_KWARGS_DEFAULT == {'normalize_y': True}
        assert instance._MODEL_CLASS == GaussianProcessRegressor

    def test__predict(self):
        # setup
        instance = MagicMock()
        instance._model_instance.predict.return_value = [[1], [2]]

        # run
        result = GaussianProcessMetaModel._predict(instance, 1)

        # assert
        instance._model_instance.predict.assert_called_once_with(1, return_std=True)
        np.testing.assert_array_equal(result, np.array([[1, 2]]))

class TestGaussianCopulaProcessMetaModel(TestCase):

    def test___init__(self):
        # run
        instance = GaussianCopulaProcessMetaModel()
        # assert
        assert instance._MODEL_KWARGS_DEFAULT == {'normalize_y': True}
        assert instance._MODEL_CLASS == GaussianProcessRegressor

    def test__trasnform(self):
        # setup
        instance = MagicMock()
        trials = np.array([
            [0.1, 0.8, 0.2],
            [0.7, 0.6, 0.4],
            [0.4, 0.2, 0.3],
            [0.7, 0.8, 0.9],
            [0.2, 0.3, 0.4]
        ])

        distributions = []
        for column in trials.T:
            distribution = Univariate()
            distribution.fit(column)
            distributions.append(distribution)

        instance._distributions = distributions

        # run
        result = GaussianCopulaProcessMetaModel._transform(instance, trials)

        # assert
        expected_result = np.array([
            [-0.93051407, 0.72584367, -1.05823838],
            [0.78865964, 0.1155097, 0.3732126],
            [-0.04619363, -0.96388991, -0.49278658],
            [0.78865964, 0.72584367, 1.82607428],
            [-0.60472608, -0.66069297, 0.3732126]
        ])

        np.testing.assert_allclose(result, expected_result)

    @patch('btb.tuning.metamodels.gaussian_process.super')
    def test__fit(self, mock_super):
        # setup
        instance = GaussianCopulaProcessMetaModel()
        trials = np.array([
            [0.1, 0.8, 0.2],
            [0.7, 0.6, 0.4],
            [0.4, 0.2, 0.3],
            [0.7, 0.8, 0.9],
            [0.2, 0.3, 0.4]
        ])
        scores = np.array([0.1, 0.4, 0.6, 0.8, 0.9])

        # run
        instance._fit(trials, scores)

        # assert
        expected_trials = np.array([
            [-0.93051407, 0.72584367, -1.05823838],
            [0.78865964, 0.1155097, 0.3732126],
            [-0.04619363, -0.96388991, -0.49278658],
            [0.78865964, 0.72584367, 1.82607428],
            [-0.60472608, -0.66069297, 0.3732126]
        ])
        expected_scores = np.array([-1.15916747, -0.43719902, 0.0415104, 0.57965234, 0.87915571])

        mock_fit_call = mock_super.return_value._fit.call_args_list
        np.testing.assert_allclose(expected_trials, mock_fit_call[0][0][0])
        np.testing.assert_allclose(expected_scores, mock_fit_call[0][0][1], rtol=1e-06)

    def test__fit_inconsistent_numbers_of_samples(self):
        """Fitting the GP model with inconsistent number of samples raises ValueError."""
        # setup
        instance = GaussianCopulaProcessMetaModel()
        trials = np.array([
            [0.1, 0.8, 0.2],
            [0.7, 0.6, 0.4],
            [0.4, 0.2, 0.3],
            [0.7, 0.8, 0.9],
            [0.2, 0.3, 0.4]
        ])
        scores = np.array([0.1, 0.6, 0.8, 0.9])

        # run
        with self.assertRaises(ValueError):
            instance._fit(trials, scores)

    def test__predict_one_candidate(self):
        """Test the prediction of one candidate."""
        # setup
        instance = GaussianCopulaProcessMetaModel()
        trials = np.array([
            [0.1, 0.8, 0.2],
            [0.7, 0.6, 0.4],
            [0.4, 0.2, 0.3],
            [0.7, 0.8, 0.9],
            [0.2, 0.3, 0.4]
        ])
        scores = np.array([0.1, 0.4, 0.6, 0.8, 0.9])

        candidates = np.array([[0.2, 0.8, 0.4]])
        instance._fit(trials, scores)

        # run
        predicted_scores = instance._predict(candidates)

        # assert
        expected_scores = np.array([0.54393124])

        np.testing.assert_allclose(expected_scores, predicted_scores)

    def test__predict_candidate_gt_one(self):
        """Test the prediction of multiple candidates."""
        # setup
        instance = GaussianCopulaProcessMetaModel()
        trials = np.array([
            [0.1, 0.8, 0.2],
            [0.7, 0.6, 0.4],
            [0.4, 0.2, 0.3],
            [0.7, 0.8, 0.9],
            [0.2, 0.3, 0.4]
        ])
        scores = np.array([0.1, 0.4, 0.6, 0.8, 0.9])

        candidates = np.array([
            [0.2, 0.8, 0.4],
            [0.1, 0.8, 0.2]
        ])
        instance._fit(trials, scores)

        # run
        predicted_scores = instance._predict(candidates)

        # assert
        expected_scores = np.array([0.54393124, 0.1])

        np.testing.assert_allclose(expected_scores, predicted_scores)


# if you want to use ec2 instance, please use following commands in cli to load chrome driver;

# bash:

# curl https://intoli.com/install-google-chrome.sh | bash
# google-chrome --version
# wget https://chromedriver.storage.googleapis.com/88.0.4324.96/chromedriver_linux64.zip
# sudo yum install unzip
# unzip chromedriver_linux64

# if you are working on local machine;

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path="/Users/m.altun/clarus/devops/04feb_selenium/second_test/chromedriver")

base_url = "https://clarusway.com/"

driver.get(base_url)

element = driver.find_element_by_id("menu-item-2808")
print("has aws-devops button shown? ---> ", element.is_displayed())
time.sleep(5)
driver.quit()


def izloci_besedo(beseda):
    n = 0

    for crka in beseda:
        if crka.isalnum() == False:
            n = n + 1
        if crka.isalnum() == True:
            break

    beseda1 = beseda[n:]
    beseda2 = beseda1[::-1]
    n = 0

    for crka in beseda2:
        if crka.isalnum() == False:
            n = n + 1
        if crka.isalnum() == True:
            break
    beseda1 = beseda2[n:]

    return(beseda1[::-1])

"""------------------------------------------------"""

from collections import defaultdict

def besedilo(tvit):
    return tvit.split(": ", 1)[1]

def zadnji_tvit(tviti):
    slovar = {}
    for tvit in tviti:
        ime = tvit.split(":")[0]
        slovar[ime] = besedilo(tvit)
    return slovar

def prvi_tvit(tviti):
    slovar = {}
    for tvit in tviti:
        ime = tvit.split(":")[0]
        if ime not in slovar:
            slovar[ime] = besedilo(tvit)
        else:
            pass

    return slovar

def prestej_tvite(tviti):
    seznam = []
    slovar = defaultdict(list)
    for tvit in tviti:
        seznam.append(tvit.split((": "), 1)[0])
        slovar = defaultdict(int)
        for ime in seznam:
            slovar[ime] += 1

    return slovar

def omembe(tviti):
    seznam = []
    slovar = defaultdict(list)
    for tvit in tviti:
        seznam.append(tvit.split(": ", 1))
        for ime, tvit1 in seznam:
            seznam1 = tvit1.split()
        for beseda in seznam1:
            seznam1 = slovar[ime]
            if beseda[0] == "@" not in seznam1:
                seznam1.append(izloci_besedo(beseda[1:]))
                slovar[ime] = seznam1
    return slovar

def neomembe(ime, omembe):
    seznam = []
    for kljuc in omembe:
        if kljuc != ime and kljuc not in omembe[ime]:
            seznam.append(kljuc)

    return seznam


import argparse
from model.layers import GraphSpectralFilterLayer, AnalysisFilter
from model.spectral_filter import Graph
import torch
import torch.nn.functional as F
from random import seed as rseed
from numpy.random import seed as nseed
from webkb import get_dataset, run
from ax import optimize
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, required=True)
parser.add_argument('--trials', type=int, default=20)
arg = parser.parse_args()

args = {
    'dataset': arg.dataset,
    'runs': 1,
    'epochs': 1000,
    'alpha': 0.2,
    'seed': 729,
    'lr': 0.005,
    'weight_decay': 0.0005,
    'patience': 50,
    'hidden': 32,
    'heads': 16,
    'dropout': 0.8,
    'normalize_features': True,
    'pre_training': True,
    'cuda': True,
    'chebyshev_order': 13,
    'edge_dropout': 0,
    'node_feature_dropout': 0,
    'filter': 'analysis'
}

def decimation(args):
    print(args)
    rseed(args['seed'])
    nseed(args['seed'])
    torch.manual_seed(args['seed'])

    args['cuda'] = args['cuda'] and torch.cuda.is_available()

    # if args['cuda']:
    #     print("-----------------------Training on CUDA-------------------------")

    if args['cuda']:
        torch.cuda.manual_seed(args['seed'])
        torch.set_default_tensor_type('torch.cuda.FloatTensor')

    class Net(torch.nn.Module):
        def __init__(self, dataset):
            super(Net, self).__init__()
            data = dataset.data
            adj = torch.sparse_coo_tensor(data.edge_index, torch.ones(data.num_edges))
            self.G = Graph(adj)
            self.G.estimate_lmax()

            self.analysis = GraphSpectralFilterLayer(self.G, dataset.num_node_features, args['hidden'],
                                                     dropout=args['dropout'], out_channels=args['heads'], filter=args['filter'],
                                                     pre_training=args['pre_training'], device='cuda' if args['cuda'] else 'cpu',
                                                     alpha=args['alpha'], chebyshev_order=args['chebyshev_order'])
            # self.mlp = nn.Sequential(nn.Linear(args['hidden * args['heads, 128),
            #                             nn.ReLU(inplace=True),
            #                             nn.Linear(128, 64),
            #                             nn.ReLU(inplace=True),
            #                             nn.Linear(64, 32),
            #                             nn.ReLU(inplace=True),
            #                             nn.Linear(32, dataset.num_classes),
            #                             nn.ReLU(inplace=True))

            # self.W = torch.zeros(args['hidden * args['heads, dataset.num_classes)

            self.synthesis = GraphSpectralFilterLayer(self.G, args['hidden'] * args['heads'], dataset.num_classes, filter=args['filter'],
                                                      device='cuda' if args['cuda'] else 'cpu', dropout=args['dropout'],
                                                      out_channels=1, alpha=args['alpha'], pre_training=False,
                                                      chebyshev_order=args['chebyshev_order'])

        def reset_parameters(self):
            self.analysis.reset_parameters()
            # torch.nn.init.xavier_uniform_(self.W.data, gain=1.414)
            # for layer in self.mlp:
            #     if hasattr(layer, 'reset_parameters'):
            #         layer.reset_parameters()
            self.synthesis.reset_parameters()

        def forward(self, data):
            x = data.x
            x = F.dropout(x, p=args['dropout'], training=self.training)
            x, att1 = self.analysis(x)
            x = F.dropout(x, p=args['dropout'], training=self.training)
            x, att2 = self.synthesis(x)
            x = F.elu(x)
            # x = F.elu(x.mm(self.W))
            # x = self.mlp(x)
            return F.log_softmax(x, dim=1), att1, att2

    use_dataset = lambda: get_dataset(args['dataset'], args['normalize_features'], edge_dropout=args['edge_dropout'],
                                      permute_masks=None, cuda=args['cuda'],
                                      node_feature_dropout=args['node_feature_dropout'], self_loop=args['self_loop'])

    return run(use_dataset, Net, args['runs'], args['epochs'], args['lr'], args['weight_decay'],
        args['patience'], None)

best_parameters, best_values, _, _ = optimize(
 parameters=[{'name': 'dataset', 'type': 'fixed', 'value': args['dataset']},
    {'name': 'runs', 'type': 'fixed', 'value': 1},
    {'name': 'epochs', 'type': 'fixed', 'value': 2000},
    {'name': 'alpha', "type": "fixed", "value": 0.2},
    {'name': 'seed', 'type': 'fixed', 'value': 729},
    {'name': 'lr', 'type': 'range', "type": "range", "bounds": [0.001, 0.01], "log_scale": True},
    {'name': 'weight_decay', 'type': 'range', "bounds": [0.000001, 0.005], "log_scale": True},
    {'name': 'patience', 'type': 'fixed', 'value': 100},
    {'name': 'hidden', 'type': 'range', "bounds": [16, 256], "log_scale": True},
    {'name': 'heads', 'type': 'range', "bounds": [1, 18]},
    {'name': 'dropout', "type": "range", "bounds": [0.1, 0.9]},
    {'name': 'self_loop', "type": "choice", "values": [True, False]},
    {'name': 'normalize_features', 'type': 'fixed', 'value': True},
    {'name': 'pre_training', 'type': 'fixed', 'value': False},
    {'name': 'cuda', 'type': 'fixed', 'value': args['cuda']},
    {'name': 'chebyshev_order', 'type': 'fixed', "value": 16},
    {'name': 'edge_dropout', 'type': 'fixed', 'value': 0},
    {'name': 'node_feature_dropout', 'type': 'fixed', 'value': 0},
    {'name': 'filter', 'type': 'fixed', 'value': 'analysis'}],
    evaluation_function=decimation,
    total_trials=arg.trials,
    minimize=False)

print(best_parameters, best_values)


import libtmux

from pmuxy.config import Config

class Pmuxy:

    def __init__(self, config: Config, session: libtmux.Session):
        self.config = config
        self.session = session

    def config_options(self):
        return self.config.config_options()

    def open(self, config_file):
        props = self.config.read_config(config_file)

        window = self.session.new_window(
            window_name=props.get('window_name', config_file),
            attach=props.get('attach', True)
        )

        tmux_cmds = props.get('tmux_commands', [])
        for cmd in tmux_cmds:
            head, *tail = cmd.split(' ')
            window.cmd(head, *tail)

        pane = window.panes[0]
        shell_cmds = props.get('shell_commands', [])

        for cmd in shell_cmds: pane.send_keys(cmd)
        if shell_cmds: pane.send_keys('clear')

    def list_windows(self):
        return self.session.windows


# -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 15:30:59 2020

@author: dalry
"""
import matplotlib.pyplot
import agentframework
import csv

#open the csv file
f = open('in.txt', newline='')      # open file
reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)

environment = []
for row in reader:				# for each row in csv file
    rowlist = []                # make a new list
    for value in row:			# for each value
        rowlist.append(value)   # append value to the rowlist
    environment.append(rowlist) # append the rowlist to the environment
f.close()

# Calculate the distance between agents
def distance_between(agents_row_a, agents_row_b):
    return (((agents_row_a._x - agents_row_b._x)**2) +
    ((agents_row_a._y - agents_row_b._y)**2))**0.5

# Setup the list of agents and the iterations to run through
num_of_agents = 10
num_of_iterations = 100
agents = []

# Make the agents.
for i in range(num_of_agents):
    agents.append(agentframework.Agent(environment, agents))

# Move the agents.
for j in range(num_of_iterations):
    for i in range(num_of_agents):
        agents[i].move()
        agents[i].eat()

# Plot the agents
matplotlib.pyplot.xlim(0, 99)
matplotlib.pyplot.ylim(0, 99)
matplotlib.pyplot.imshow(environment)
for i in range(num_of_agents):
    matplotlib.pyplot.scatter(agents[i]._x,agents[i]._y)
matplotlib.pyplot.show()

#n Write the new environment to csv
a = []
a.append(environment)
f = open("anotherfile.txt", 'w')
for line in a:
	f.write(str(line))
f.close()

# Write the total amount stored by each agent on a line in a new file
b = []
for i in range(num_of_agents):
    b.append(agents[i].store)
f = open("store.txt", 'w')
for line in b:
    f.write(str(line))
    f.write("\n")
f.close()


# -*- coding: utf-8 -*-
from zope.interface import implements
from AccessControl import ClassSecurityInfo
from Products.Archetypes import atapi
from archetypes.referencebrowserwidget.widget import ReferenceBrowserWidget
from Products.OrderableReferenceField import OrderableReferenceField
from Products.OrderableReferenceField import OrderableReferenceWidget
from plone.app.blob.field import ImageField

from Products.minaraad import MinaraadMessageFactory as _
from Products.minaraad.interfaces import IAdvisory
from Products.minaraad.Attachmentsmixin import Attachmentsmixin
from Products.minaraad.ImageAttachmentsmixin import ImageAttachmentsmixin
from Products.minaraad.ThemeMixin import ThemeParentMixin
from Products.minaraad.config import PROJECTNAME
from Products.minaraad.content.interfaces import IUseContact
from Products.minaraad.content.contacts import contacts_schema
from Products.minaraad.utils import list_viewable

# Do NOT import this as underscore, as i18ndude will then pick it up
# for the wrong domain.
from minaraad.projects import MinaraadProjectMessageFactory

schema = atapi.Schema((

    atapi.DateTimeField(
        name='date',
        required=True,
        widget=atapi.CalendarWidget(
            label='Date',
            label_msgid='minaraad_label_date',
            i18n_domain='minaraad',
        )
    ),

    atapi.TextField(
        name='description',
        widget=atapi.TextAreaWidget(
            label='Description',
            label_msgid='minaraad_label_description',
            i18n_domain='minaraad',
        )
    ),

    atapi.StringField(
        name='product_number',
        required=False,
        validators=('projectNumber3Digits', ),
        widget=atapi.StringWidget(
            label=MinaraadProjectMessageFactory(
                u'label_product_number',
                default=u'Product number')
        )
    ),

    atapi.TextField(
        name='popular_summary',
        allowable_content_types=('text/html', 'text/plain'),
        widget=atapi.RichWidget(
            label=_('Popular summary'),
        ),
        default_content_type='text/html',
        default_output_type='text/x-html-safe',
    ),

    # Body (which already existed) serves as the summary (of the attachment,
    # summary is shown in the listings).
    atapi.TextField(
        name='body',
        allowable_content_types=('text/html', 'text/plain'),
        widget=atapi.RichWidget(
            label='Summary',
            label_msgid='minaraad_label_summary',
            i18n_domain='minaraad',
        ),
        default_content_type='text/html',
        default_output_type='text/x-html-safe',
    ),
    # Deprecated, can be removed after the final release
    ImageField(
        name='foto',
        widget=atapi.ImageWidget(
            label="Photo",
            label_msgid='minaraad_label_foto',
            i18n_domain='minaraad',
            visible=False
        ),
        storage=atapi.AttributeStorage(),
        sizes={'foto': (300, 300)},

    ),

    OrderableReferenceField(
        name='contact',
        vocabulary_display_path_bound="-1",
        widget=OrderableReferenceWidget(
            visible=False,
            label='Contact',
            label_msgid='minaraad_label_contact',
            i18n_domain='minaraad',
            base_query={
                'sort_on': 'sortable_title',
            },
        ),
        allowed_types=('ContactPerson', ),
        multiValued=1,
        relationship='advisory_contact'
    ),

    atapi.ReferenceField(
        name='relatedDocuments',
        vocabulary_display_path_bound="-1",
        widget=ReferenceBrowserWidget(
            label='Related Documents',
            label_msgid='minaraad_label_related_documents',
            description="Related and published digibib documents and files",
            description_msgid="minaraad_help_related_documents",
            i18n_domain='minaraad',
            # ATReferenceBrowser specific additions:
            startup_directory='/',
            restrict_browsing_to_startup_directory=0,
            only_for_review_states=('published', ),
            show_review_state=1,
            allow_search=1,
            allow_browse=1,
            show_indexes=0,
            force_close_on_insert=0,
        ),
        allowed_types=('Document', 'File', 'FileAttachment',
                       'Advisory', 'Study', 'MREvent'),
        multiValued=True,
        relationship='related_documents'
    ),

    atapi.ReferenceField(
        name='project',
        allowed_types=('Project',),
        multiValued=False,
        relationship='related_project',
    ),
),
)

Advisory_schema = (
    getattr(Attachmentsmixin, 'schema', atapi.Schema(())).copy() +
    getattr(ImageAttachmentsmixin, 'schema', atapi.Schema(())).copy() +
    schema.copy() +
    contacts_schema.copy()
)
Advisory_schema['description'].isMetadata = False
# Hide the description field.
Advisory_schema['description'].widget.visible = {
    'edit': 'hidden', 'view': 'invisible'}
Advisory_schema['project'].widget.visible = {
    'edit': 'invisible', 'view': 'invisible'}

Advisory_schema.moveField('displayAttachments', after="body")
Advisory_schema.moveField('displayImages', after='displayAttachments')
Advisory_schema.moveField('coordinator', after="displayImages")
Advisory_schema.moveField('authors', after="coordinator")

class Advisory(Attachmentsmixin, ThemeParentMixin):
    """An advisory
    """
    implements(IAdvisory, IUseContact)
    security = ClassSecurityInfo()
    archetype_name = 'Advisory'
    portal_type = 'Advisory'
    _at_rename_after_creation = True
    schema = Advisory_schema

    def getRelatedDocuments(self):
        """Get the documents from the relatedDocuments field.

        Only get those that the user is allowed to access.

        Adapted from
        Products/CMFPlone/skins/plone_scripts/computeRelatedItems.py
        """
        docs = self.getField('relatedDocuments').get(self)
        return list_viewable(docs)

atapi.registerType(Advisory, PROJECTNAME)


from __future__ import print_function

import os
import platform
import random

from fabric.api import cd, env, execute, local, run, task
from fabric.colors import green, red

CONFIG = {
    'host': 'deploy@',
    'project': 'box',
    'branch': 'master',
}

CONFIG.update({
    'sass': '{project}/static/{project}'.format(**CONFIG),
    'service': 'www-{project}'.format(**CONFIG),
    'folder': 'www/{project}/'.format(**CONFIG),
})

env.forward_agent = True
env.hosts = [CONFIG['host']]

def _configure(fn):
    def _dec(string, *args, **kwargs):
        return fn(string.format(**CONFIG), *args, **kwargs)
    return _dec

local = _configure(local)
cd = _configure(cd)
run = _configure(run)

@task
def dev():
    import socket
    from threading import Thread
    jobs = [
        Thread(target=lambda: execute('watch_styles')),
        Thread(target=lambda: execute('runserver')),
    ]
    try:
        socket.create_connection(('localhost', 6379), timeout=0.1).close()
    except socket.error:
        jobs.append(Thread(target=lambda: local('redis-server')))
    [j.start() for j in jobs]
    [j.join() for j in jobs]

@task(alias='ws')
def watch_styles():
    local('cd {sass} && grunt')

@task(alias='rs')
def runserver(port=8000):
    local('venv/bin/python -Wall manage.py runserver 0.0.0.0:{}'.format(port))

@task
def deploy_styles():
    local('cd {sass} && grunt build')
    local('rsync -avz {sass}/css {host}:{folder}static/{project}/')
    local(
        'rsync -avz {sass}/bower_components {host}:{folder}static/{project}/')

@task
def deploy_code():
    local('flake8 .')
    local('git push origin {branch}')
    with cd('{folder}'):
        run('git fetch')
        run('git reset --hard origin/{branch}')
        run('find . -name "*.pyc" -delete')
        run('venv/bin/pip install -r requirements/live.txt')
        run('venv/bin/python manage.py syncdb')
        run('venv/bin/python manage.py migrate')
        run('venv/bin/python manage.py collectstatic --noinput')
        run('sudo service {service} restart')

@task
def deploy():
    execute('deploy_styles')
    execute('deploy_code')

@task
def setup():
    if os.path.exists('venv'):
        print(red('It seems that this project is already set up, aborting.'))
        return 1

    local('virtualenv venv')
    if platform.system() == 'Darwin' and platform.mac_ver()[0] >= '10.9':
        local(
            'export CFLAGS=-Qunused-arguments'
            ' && export CPPFLAGS=-Qunused-arguments'
            ' && venv/bin/pip install -r requirements/dev.txt')
    else:
        local('venv/bin/pip install -r requirements/dev.txt')

    with open('box/local_settings.py', 'w') as f:
        rand = random.SystemRandom()
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        secret_key = ''.join(rand.choice(chars) for i in range(50))
        f.write(
            'SECRET_KEY = \'%s\'\n'
            'ALLOWED_HOSTS = [\'*\']\n'
            'RAVEN_CONFIG = {}\n' % secret_key)

    local('venv/bin/python manage.py syncdb --all --noinput')
    local('venv/bin/python manage.py migrate --all --fake')
    local('cd {sass} && npm install')
    local('cd {sass} && bower install')

    print(green('Initial setup has completed successfully!', bold=True))
    print(green('Next steps:'))
    print(green(
        '- Create a superuser: venv/bin/python manage.py createsuperuser'))
    print(green('- Run the development server: fab dev'))


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

################################################################################
#
# Copyright 2010-2014 Carlos Ramisch, Vitor De Araujo, Silvio Ricardo Cordeiro,
# Sandra Castellanos
#
# ft_arff.py is part of mwetoolkit
#
# mwetoolkit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mwetoolkit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with mwetoolkit.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
This module provides classes to manipulate files that are encoded in the
"ARFF" filetype, which is used by the WEKA machine learning toolkit.

You should use the methods in package `filetype` instead.
"""

from . import _common as common

################################################################################

class ArffInfo(common.FiletypeInfo):
    r"""FiletypeInfo subclass for ARFF files."""
    description = "ARFF file type, as defined by the WEKA toolkit"
    filetype_ext = "ARFF"

    comment_prefix = "%"

    def operations(self):
        return common.FiletypeOperations(ArffChecker, None, ArffPrinter)

INFO = ArffInfo()

################################################################################

class ArffChecker(common.AbstractChecker):
    r"""Checks whether input is in ARFF format."""
    def matches_header(self, strict):
        return not strict

################################################################################

class ArffPrinter(common.AbstractPrinter):
    valid_categories = ["candidates"]

    def __init__(self, ctxinfo, category, relation_name="MWETOOLKIT_RELATION", **kwargs):
        super(ArffPrinter, self).__init__(ctxinfo, category, **kwargs)
        self.relation_name = relation_name
        self.all_feats = []

    def handle_meta(self, meta, ctxinfo):
        """When the `Meta` header is read, this function generates a
        corresponding header for the ARFF file. The header includes the name of
        the relation and a description of the attributes. This description is
        based on the `MetaFeat' and `MetaTPClass` entries of the header. If you
        provided invalid types for the features or the TP base, the generated
        ARFF file will not be recognized by WEKA. If necessary, correct it
        manually.

        @param meta The `Meta` header that is being read from the file.
        """
        self.add_string(ctxinfo, "@relation {}\n".format(self.relation_name))
        for meta_feat in meta.meta_feats:
            self.add_string(ctxinfo, "@attribute {} {}\n".format(
                    meta_feat.name, meta_feat.feat_type))
            # features that will be considered in each candidate
            self.all_feats.append(meta_feat.name)
        for meta_tpclass in meta.meta_tpclasses:
            self.add_string(ctxinfo, "@attribute {} {}\n".format(
                    meta_tpclass.name, meta_tpclass.feat_type))
        self.add_string(ctxinfo, "@data\n")

    def handle_candidate(self, candidate, ctxinfo):
        """For each `Candidate`, print a comma-separated line with its feature
        values as described by the meta-features in the header. If a feature has
        no meta-feature header, it will be ignored. If a feature has an
        associated meta-feature header but no feature value, it will be
        considered as a missing value "?" in the ARFF file. The True Positive
        base are also considered as features in this context and are printed
        after the standard features of the candidate.

        @param candidate The `Candidate` that is being read from the XML file.
        """
        line = []
        for feat_name in self.all_feats:
            feat_value = candidate.get_feat_value(feat_name)
            if type(feat_value) == float:
                feat_value = "{:.8f}".format(feat_value)
            else:
                feat_value = str(feat_value)
            line.append(feat_value)
        line.extend(tpc.feat_type for tpc in candidate.tpclasses)
        self.add_string(ctxinfo, ",".join(line), "\n")


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

import numpy as np
from tests.common.tensorio import compare_tensor
from akg.utils import kernel_exec as utils
from tests.common.test_op.ascend import two2fractal
from tests.common.base import get_rtol_atol
from tests.common.gen_random import random_gaussian

def two2fractal_execute(dim_size, format, dtype, attrs):
    # Generate data
    shape = dim_size
    support_formats = ['zN', 'zZ', 'nZ']
    assert format in support_formats
    assert len(shape) >= 2 and len(shape) <= 4

    # mod launch
    op_attrs = [format]

    default_attrs = { "enable_polytops" : "never" }
    attrs["pragma_disable_whole_component"] = False
    attrs.update(default_attrs)
    if 'tuning' in attrs.keys():
        t = attrs.get("tuning", False)
        kernel_name = attrs.get("kernel_name", False)
        mod = two2fractal_compile(shape, dtype, op_attrs, attrs, t)
        if t:
            bench_mark, input, output = gen_data(dtype, format, shape)
            return mod, bench_mark, (input, output)
        else:
            return mod
    else:
        mod = two2fractal_compile(shape, dtype, op_attrs, attrs)
        source_code = mod.imported_modules[0].get_source()
        bench_mark, input, output = gen_data(dtype, format, shape)
        output = utils.mod_launch(mod, (input, output), expect=bench_mark)

        # compare result
        rtol, atol = get_rtol_atol("tile", dtype)
        compare_result = compare_tensor(output, bench_mark, rtol=rtol, atol=atol, equal_nan=True)
        return input, output, bench_mark, compare_result

def two2fractal_compile(shape, dtype, op_attrs, attrs, tuning=False):
    return utils.op_build_test(two2fractal.two2fractal, [shape], [dtype], op_attrs, kernel_name='two2fractal', attrs=attrs, tuning=tuning)

def gen_data(dtype, format, shape):
    input = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype)
    m, n = shape[-2], shape[-1]
    m1, n1 = m // 16, n // 16
    m0, n0 = 16, 16
    need_pad = m % 16 != 0 or n % 16 != 0
    if need_pad:
        pad_m, pad_n = (m + 15) // 16 * 16, (n + 15) // 16 * 16
        pad_shape = [x for x in shape]
        pad_shape[-1] = pad_n
        pad_shape[-2] = pad_m
        pad_input = np.zeros(pad_shape).astype(dtype)
        if len(shape) == 2:
            pad_input[:m, :n] = input
        elif len(shape) == 3:
            pad_input[:, :m, :n] = input
        elif len(shape) == 4:
            pad_input[:, :, :m, :n] = input
        m1, n1 = pad_m // 16, pad_n // 16
        reshape_shape = shape[:-2] + [m1, m0, n1, n0]
        reshape_input = pad_input.reshape(reshape_shape)
    else:
        reshape_shape = shape[:-2] + [m1, m0, n1, n0]
        reshape_input = input.reshape(reshape_shape)
    if format == 'zN':
        transpose_axis = [2, 0, 1, 3]
        new_shape = [n1, m1, m0, n0]
    elif format == 'zZ':
        transpose_axis = [0, 2, 1, 3]
        new_shape = [m1, n1, m0, n0]
    elif format == 'nZ':
        transpose_axis = [0, 2, 3, 1]
        new_shape = [m1, n1, n0, m0]
    transpose_axis = [x + len(shape) - 2 for x in transpose_axis]
    transpose_axis = [x for x in range(len(shape) - 2)] + transpose_axis
    new_shape = shape[:-2] + new_shape
    bench_mark = reshape_input.transpose(transpose_axis).astype('float16')
    # fractal only support float16
    output = np.full(new_shape, np.nan, 'float16')
    return bench_mark, input, output


from typing import List

class Solution:
    def splitArray(self, nums: List[int], m: int) -> int:

        prefix_sum = [nums[0]]
        M = m
        for n in nums[1:]:
            prefix_sum.append(prefix_sum[-1] + n)

        solution = [p for p in prefix_sum]
        new_solution = [0] * len(nums)

        import math
        for m in range(1, M):
            for n in range(1, len(nums)):
                min_value = math.inf
                for k in range(n-1, -1, -1):
                    x = solution[k]
                    y = prefix_sum[n] - prefix_sum[k]
                    max_value = max(x, y)
                    min_value = min(max_value, min_value)
                new_solution[n] = min_value
            solution = new_solution
            new_solution = [0] * len(nums)
        return solution[-1]

    # time limited exceeded
    def splitArraydfs(self, nums, k, p):
        import math
        if not nums[p:]:
            return -math.inf
        if k == 1:
            return sum(nums[p:])

        min_value = math.inf
        for i in range(p+1, len(nums) + 1):
            curr = sum(nums[p:i])
            child_sum = self.splitArraydfs(nums, k-1, i)
            min_value = min(max(curr, child_sum), min_value)
        return min_value

if __name__ == '__main__':
    nums = [7, 2, 5, 10, 8]
    #nums = [1, 2]
    print(Solution().splitArraydfs(nums, 4, 0))


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /home/jiangyongkang/anaconda3/lib/python3.7/site-packages/jyk/logging/core.py
# Compiled at: 2020-04-01 00:29:17
# Size of source mod 2**32: 4976 bytes
import os, time, json, copy, threading, logging, logging.handlers
from pathlib import Path
from .colors import red, yellow, cyan
from .formatter import JsonFormatter
log = logging.getLogger(__name__)
_tasks = {}
_loggers = {}
LOG_ROOT = os.getcwd()

class FormatterMode(object):
    BRIEF = 'brief'
    INTACT = 'intact'

class Singleton(type):
    __doc__ = 'Singleton.\n    @see: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python\n    '
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = (super(Singleton, cls).__call__)(*args, **kwargs)
        return cls._instances[cls]

class LogRootPath(metaclass=Singleton):
    __doc__ = 'set jyk logging Root\n    Args:\n        log_root: `PathLike` Log Root Path\n    '
    _root = None

    @classmethod
    def set(self, log_root):
        self._root = log_root

    @classmethod
    def get(self):
        if self._root is None:
            self._root = LOG_ROOT
        return self._root

def getLogPath(*args, **kwargs):
    """
    Returns:
        absolute path of file named name in the jyk log directory
    """
    _ROOT = Path(LogRootPath.get())
    if kwargs.get('root'):
        return _ROOT
    return (_ROOT.joinpath)(*args)

class DatabaseHandler(logging.Handler):
    __doc__ = 'Logging to database'

    def emit(self, recored):
        raise NotImplementedError

class TaskHandler(logging.Handler):
    __doc__ = 'Per-task logger.\n    Used to log all task specific events to a per-task jyk.log log file.\n    '

    def emit(self, record):
        task_id = _tasks.get(threading.get_ident())
        if not task_id:
            return
        with open(getLogPath('jyk.log', analysis=task_id), 'a+b') as (f):
            f.write('%s\n' % self.format(record))

class ConsoleHandler(logging.StreamHandler):
    __doc__ = 'Logging to console handler'

    def emit(self, record):
        colored = copy.copy(record)
        if record.levelname == 'WARNING':
            colored.msg = yellow(record.msg)
        else:
            if record.levelname == 'ERROR' or record.levelname == 'CRITICAL':
                colored.msg = red(record.msg)
            else:
                if 'analysis completed' in record.msg:
                    colored.msg = cyan(record.msg)
                else:
                    colored.msg = record.msg
        logging.StreamHandler.emit(self, colored)

def taskLogStart(task_id):
    """Associate a threading with a task."""
    _tasks[threading.get_ident()] = task_id

def taskLogStop(task_id):
    """Disassociate a threading from a task."""
    _tasks.pop(threading.get_ident(), None)

def initLogger(name: str, level=None, mode=FormatterMode.INTACT) -> None:
    """init Logger
    Args:
        name: name
        level: logging.level
    """
    if mode == FormatterMode.INTACT:
        formatter = logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s')
    else:
        formatter = logging.Formatter('[%(name)s]: %(message)s')
    if name == 'console':
        log = ConsoleHandler()
        log.setFormatter(formatter)
        log.setLevel(level)
    if name == 'database':
        log = DatabaseHandler()
        log.setLevel(logging.ERROR)
    if name == 'task':
        log = TaskHandler()
        log.setFormatter(formatter)
    if name.endswith('.json'):
        j = JsonFormatter()
        log = logging.handlers.WatchedFileHandler(getLogPath(name))
        log.setFormatter(j)
    if name.endswith('.log'):
        log = logging.handlers.WatchedFileHandler(getLogPath(name))
        log.setFormatter(formatter)
        log.setLevel(level)
    _loggers[name] = log
    logging.getLogger().addHandler(log)

def logger(message, *args, **kwargs):
    """Log a message to specific logger instance."""
    logfile = kwargs.pop('logfile', None)
    record = logging.LogRecord(None, logging.INFO, None, None, message, args, None, None)
    record.asctime = '%s,%03d' % (
     time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(record.created)), record.msecs)
    record.message = record.getMessage()
    record.__dict__.update(kwargs)
    for key, value in _loggers.items():
        if logfile:
            if key == logfile:
                value.handle(record)
        if logfile is None and key.endswith('.json'):
            value.handle(record)

def initConsoleLogging(level=logging.INFO, mode=FormatterMode.BRIEF):
    """Initializes logging only to console.
    Args:
        level: logging.level
    """
    logging.getLogger().setLevel(logging.DEBUG)
    initLogger('console', level, mode)

def initLogging(name, level=logging.INFO, mode=FormatterMode.INTACT):
    """Initializes logging.
    Args:
        level: logging.level
    """
    logging.getLogger().setLevel(logging.DEBUG)
    initLogger(name, level, mode)

__all__ = [
 'initConsoleLogging', 'initLogging', 'LogRootPath']


# uncompyle6 version 3.7.4
# Python bytecode 3.4 (3310)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/utils/label_map_util_test.py
# Compiled at: 2018-06-15 01:29:01
# Size of source mod 2**32: 4725 bytes
"""Tests for object_detection.utils.label_map_util."""
import os, tensorflow as tf
from google.protobuf import text_format
from object_detection.protos import string_int_label_map_pb2
from object_detection.utils import label_map_util

class LabelMapUtilTest(tf.test.TestCase):

    def _generate_label_map(self, num_classes):
        label_map_proto = string_int_label_map_pb2.StringIntLabelMap()
        for i in range(1, num_classes + 1):
            item = label_map_proto.item.add()
            item.id = i
            item.name = 'label_' + str(i)
            item.display_name = str(i)

        return label_map_proto

    def test_get_label_map_dict(self):
        label_map_string = "\n      item {\n        id:2\n        name:'cat'\n      }\n      item {\n        id:1\n        name:'dog'\n      }\n    "
        label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt')
        with tf.gfile.Open(label_map_path, 'wb') as (f):
            f.write(label_map_string)
        label_map_dict = label_map_util.get_label_map_dict(label_map_path)
        self.assertEqual(label_map_dict['dog'], 1)
        self.assertEqual(label_map_dict['cat'], 2)

    def test_load_bad_label_map(self):
        label_map_string = "\n      item {\n        id:0\n        name:'class that should not be indexed at zero'\n      }\n      item {\n        id:2\n        name:'cat'\n      }\n      item {\n        id:1\n        name:'dog'\n      }\n    "
        label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt')
        with tf.gfile.Open(label_map_path, 'wb') as (f):
            f.write(label_map_string)
        with self.assertRaises(ValueError):
            label_map_util.load_labelmap(label_map_path)

    def test_keep_categories_with_unique_id(self):
        label_map_proto = string_int_label_map_pb2.StringIntLabelMap()
        label_map_string = "\n      item {\n        id:2\n        name:'cat'\n      }\n      item {\n        id:1\n        name:'child'\n      }\n      item {\n        id:1\n        name:'person'\n      }\n      item {\n        id:1\n        name:'n00007846'\n      }\n    "
        text_format.Merge(label_map_string, label_map_proto)
        categories = label_map_util.convert_label_map_to_categories(label_map_proto, max_num_classes=3)
        self.assertListEqual([
         {'id': 2,
          'name': 'cat'},
         {'id': 1,
          'name': 'child'}], categories)

    def test_convert_label_map_to_categories_no_label_map(self):
        categories = label_map_util.convert_label_map_to_categories(None, max_num_classes=3)
        expected_categories_list = [
         {'name': 'category_1',
          'id': 1},
         {'name': 'category_2',
          'id': 2},
         {'name': 'category_3',
          'id': 3}]
        self.assertListEqual(expected_categories_list, categories)

    def test_convert_label_map_to_coco_categories(self):
        label_map_proto = self._generate_label_map(num_classes=4)
        categories = label_map_util.convert_label_map_to_categories(label_map_proto, max_num_classes=3)
        expected_categories_list = [
         {'name': '1',
          'id': 1},
         {'name': '2',
          'id': 2},
         {'name': '3',
          'id': 3}]
        self.assertListEqual(expected_categories_list, categories)

    def test_convert_label_map_to_coco_categories_with_few_classes(self):
        label_map_proto = self._generate_label_map(num_classes=4)
        cat_no_offset = label_map_util.convert_label_map_to_categories(label_map_proto, max_num_classes=2)
        expected_categories_list = [
         {'name': '1',
          'id': 1},
         {'name': '2',
          'id': 2}]
        self.assertListEqual(expected_categories_list, cat_no_offset)

    def test_create_category_index(self):
        categories = [{'name': '1',  'id': 1}, {'name': '2',  'id': 2}]
        category_index = label_map_util.create_category_index(categories)
        self.assertDictEqual({1: {'name': '1',
             'id': 1},
         2: {'name': '2',
             'id': 2}}, category_index)

if __name__ == '__main__':
    tf.test.main()


def ensure(module, client):
    zone_name = module.params['zone_name']
    record_name = module.params['record_name']
    record_ttl = module.params.get('record_ttl')
    state = module.params['state']
    ipa_dnsrecord = client.dnsrecord_find(zone_name, record_name)
    module_dnsrecord = dict(record_type=module.params['record_type'], record_value=module.params['record_value'], record_ttl=to_native(record_ttl))
    changed = False
    if (state == 'present'):
        if (not ipa_dnsrecord):
            changed = True
            if (not module.check_mode):
                client.dnsrecord_add(zone_name=zone_name, record_name=record_name, details=module_dnsrecord)
        else:
            diff = get_dnsrecord_diff(client, ipa_dnsrecord, module_dnsrecord)
            if (len(diff) > 0):
                changed = True
                if (not module.check_mode):
                    client.dnsrecord_mod(zone_name=zone_name, record_name=record_name, details=module_dnsrecord)
    elif ipa_dnsrecord:
        changed = True
        if (not module.check_mode):
            client.dnsrecord_del(zone_name=zone_name, record_name=record_name, details=module_dnsrecord)
    return (changed, client.dnsrecord_find(zone_name, record_name))


from django.conf.urls import patterns, url, include
from kii.permission import views
from . import models

permissionmodel_patterns = patterns('',
    url(r'^(?P<pk>\d+)/$',
        views.PermissionMixinDetail.as_view(
            model=models.PermissionModel,
            template_name="templates/test.html"),
        name='detail'),
    url(r'^(?P<pk>\d+)/update',
        views.PermissionMixinUpdate.as_view(
            model=models.PermissionModel,
            template_name="templates/test.html"),
        name='update'),
    url(r'^(?P<pk>\d+)/delete',
        views.PermissionMixinDelete.as_view(
            model=models.PermissionModel,
            template_name="templates/test.html"),
        name='delete'),
    url(r'^$',
        views.PermissionMixinList.as_view(
            model=models.PermissionModel,
            template_name="templates/test.html"),
        name='list'),
)

urlpatterns = patterns('',

    url(
        r'^permissionmodel/',
        include(
            permissionmodel_patterns,
            namespace='permissionmodel',
            app_name='permissionmodel')
        ),
)


thisdict = {
  "First name:" : "Anna",
  "Last name:" : "Solemani",
  "Age:" : 33
}

thisdict['Last name:'] = "Romeo"

thisdict['Eye colour:'] = "Brown"

del thisdict['First name:']

print(thisdict)

for key, value in thisdict.items():
    print(key, value)

contacts = {
    "Anna" : "0539249971",
    "Dad" : "07968194985",
    "Anna UK" : "07967804143"
}

contacts["Sarah"] = "12345678"

print(contacts)

for key, value in contacts.items():
    print(key, value)

seeked_name = "Anna"
if seeked_name in contacts:
  print("Yes, 'Anna' is one of the names in this contact list.")

seeked_number = "07967804143"
if seeked_number in contacts.values():
    print("Yes, {} is in the list. It is 's number.".format(seeked_number))


from django.db import transaction
from django.core.management import CommandError, BaseCommand
from ._academic_sample_data import (
    clean_course_type, clean_rmu_roots, clean_course_group,
    create_course_type, create_rmu_roots, create_course_group,
    clean_school_year, create_school_year,
    clean_academic_year, create_academic_year,
    clean_curriculum, create_curriculum,
    create_course, clean_course
)

class Command(BaseCommand):
    help = 'Closes the specified poll for voting'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clean',
            action='store_true',
            dest='clean',
            help='Delete poll instead of closing it',
        )

    def handle(self, *args, **options):
        with transaction.atomic():
            if options['clean']:
                clean_course()
                clean_curriculum()
                clean_academic_year()
                clean_rmu_roots()
                clean_course_type()
                clean_course_group()
                clean_school_year(),
            create_school_year()
            create_rmu_roots()
            create_course_type()
            create_course_group()
            create_academic_year()
            create_curriculum()
            create_course()
            # try:
            #
            # except Exception as err:
            #     raise CommandError(err)

        self.stdout.write(self.style.SUCCESS('Successfully install academic initial data.'))


"""
coinfee.net example.
"""

import warnings
from uuid import uuid4 as random_uuid

import jinja2
import coinfee

# You should change this unless you want to make a donation.
ADDRESS = '16jCrzcXo2PxadrQiQwUgwrmEwDGQYBwZq'

# Price in Satoshis. 10,000 or more.
SATOSHIS = 10000

# See deprecation warnings in logs.
warnings.simplefilter('always')

def render(template, page={}):
    template = jinja2.Environment(
        loader=jinja2.FileSystemLoader('./')
        ).get_template(template)
    return str(template.render(page=page))

def application(env, start_response):
    """
    This is where uwsgi calls us.
    """
    def reply(status, data, headers=[]):
        """
        Need to use this as return reply().
        """
        start_response(str(status), headers)
        return data

    path = env['REQUEST_URI']

    if path == '/purchase':
        # Generate a random ID for payment.
        uuid = str(random_uuid())[:19]
        url = '/purchase/{}'.format(uuid)
        # Redirect to unique buy URL.
        return reply(307, '', [('Location', url)])
    if path.startswith('/purchase/'):
        page = {}
        page['unique'] = path[len('/purchase/'):]
        coinfee_payment = coinfee.payment(ADDRESS,
                                          SATOSHIS,
                                          page['unique'])
        page['paid'] = coinfee_payment.status
        page['address'] = coinfee_payment.address
        page['satoshis'] = coinfee_payment.satoshis
        page['bitcoins'] = "{0:.8f}".format(page['satoshis'] *
                                            0.00000001)

        return reply(200, render('purchase.html', page))
    if path == '/':
        return reply(200, render('index.html'))

    return reply(404, 'Not found.')


import speech_recognition as sr

r = sr.Recognizer()
commands = []

while True:
    with sr.Microphone() as source: # use the default microphone as the audio source
        audio = r.listen(source) # listen for the first phrase and extract it into audio data
    try:
        said = r.recognize_google(audio);
        print("You said " + said) # recognize speech using Google Speech Recognition
        #command.push(said);
    except LookupError: # speech is unintelligible
        print("Could not understand audio")


import numpy as np

from deeplearning.layers import *
from deeplearning.fast_layers import *
from deeplearning.layer_utils import *

class ThreeLayerConvNet(object):
	"""
	A three-layer convolutional network with the following architecture:

	conv - relu - 2x2 max pool - affine - relu - affine - softmax

	The network operates on minibatches of data that have shape (N, C, H, W)
	consisting of N images, each with height H and width W and with C input
	channels.
	"""

	def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7,
							 hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0,
							 dtype=np.float32):
		"""
		Initialize a new network.

		Inputs:
		- input_dim: Tuple (C, H, W) giving size of input data
		- num_filters: Number of filters to use in the convolutional layer
		- filter_size: Size of filters to use in the convolutional layer
		- hidden_dim: Number of units to use in the fully-connected hidden layer
		- num_classes: Number of scores to produce from the final affine layer.
		- weight_scale: Scalar giving standard deviation for random initialization
			of weights.
		- reg: Scalar giving L2 regularization strength
		- dtype: numpy datatype to use for computation.
		"""
		self.params = {}
		self.reg = reg
		self.dtype = dtype

		############################################################################
		# TODO: Initialize weights and biases for the three-layer convolutional		 #
		# network. Weights should be initialized from a Gaussian with standard		 #
		# deviation equal to weight_scale; biases should be initialized to zero.	 #
		# All weights and biases should be stored in the dictionary self.params.	 #
		# Store weights and biases for the convolutional layer using the keys 'W1' #
		# and 'b1'; use keys 'W2' and 'b2' for the weights and biases of the			 #
		# hidden affine layer, and keys 'W3' and 'b3' for the weights and biases	 #
		# of the output affine layer.																							 #
		############################################################################
		C, H, W = input_dim
		self.params['W1'] = np.random.normal(0, scale=weight_scale, size=(num_filters, C, filter_size, filter_size))
		self.params['W2'] = np.random.normal(0, scale=weight_scale, size=(int(num_filters*H*W*0.25), hidden_dim))
		self.params['W3'] = np.random.normal(0, scale=weight_scale, size=(hidden_dim, num_classes))

		self.params['b1'] = np.zeros(num_filters)
		self.params['b2'] = np.zeros(hidden_dim)
		self.params['b3'] = np.zeros(num_classes)
		############################################################################
		#															END OF YOUR CODE														 #
		############################################################################
		for k, v in self.params.iteritems():
			self.params[k] = v.astype(dtype)

	def loss(self, X, y=None):
		"""
		Evaluate loss and gradient for the three-layer convolutional network.

		Input / output: Same API as TwoLayerNet in fc_net.py.
		"""
		W1, b1 = self.params['W1'], self.params['b1']
		W2, b2 = self.params['W2'], self.params['b2']
		W3, b3 = self.params['W3'], self.params['b3']

		# pass conv_param to the forward pass for the convolutional layer
		filter_size = W1.shape[2]
		conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2}

		# pass pool_param to the forward pass for the max-pooling layer
		pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}

		scores = None
		############################################################################
		# TODO: Implement the forward pass for the three-layer convolutional net,  #
		# computing the class scores for X and storing them in the scores					 #
		# variable.																																 #
		############################################################################
		z1, cache1 = conv_relu_pool_forward(X, W1, b1, conv_param, pool_param)
		z2, cache2 = affine_relu_forward(z1, W2, b2)
		y3, cache3 = affine_forward(z2, W3, b3)
		scores = y3
		############################################################################
		#															END OF YOUR CODE														 #
		############################################################################

		if y is None:
			return scores

		loss, grads = 0, {}
		############################################################################
		# TODO: Implement the backward pass for the three-layer convolutional net, #
		# storing the loss and gradients in the loss and grads variables. Compute  #
		# data loss using softmax, and make sure that grads[k] holds the gradients #
		# for self.params[k]. Don't forget to add L2 regularization!							 #
		############################################################################
		loss, dout = softmax_loss(scores, y)
		loss += self.reg * 0.5 * (np.power(self.params['W3'], 2).sum() +
																np.power(self.params['W2'], 2).sum() +
																np.power(self.params['W1'], 2).sum())

		dx3, grads['W3'], grads['b3'] = affine_backward(dout, cache3)
		dx2, grads['W2'], grads['b2'] = affine_relu_backward(dx3, cache2)
		dx1, grads['W1'], grads['b1'] = conv_relu_pool_backward(dx2, cache1)
		############################################################################
		#															END OF YOUR CODE														 #
		############################################################################

		return loss, grads

def affine_relu_bn_forward(x, w, b, gamma, beta, bn_param):
	a, fc_cache = affine_forward(x, w, b)
	a, bn_cache = batchnorm_forward(a, gamma, beta, bn_param)
	out, relu_cache = relu_forward(a)

	cache = (fc_cache, bn_cache, relu_cache)
	return out, cache

def affine_relu_bn_backward(dout, cache):
	fc_cache, bn_cache, relu_cache = cache

	da = relu_backward(dout, relu_cache)
	da, dgamma, dbeta = batchnorm_backward_alt(da, bn_cache)
	dx, dw, db = affine_backward(da, fc_cache)

	return dx, dw, db, dgamma, dbeta

def affine_relu_dropout_forward(x, w, b, dropout_param):
	a, fc_cache = affine_forward(x, w, b)
	a, relu_cache = relu_forward(a)
	out, dropout_cache = dropout_forward(a, dropout_param)

	cache = (fc_cache, relu_cache, dropout_cache)
	return out, cache

def affine_relu_dropout_backward(dout, cache):
	fc_cache, relu_cache, dropout_cache = cache

	da = dropout_backward(dout, dropout_cache)
	da = relu_backward(da, relu_cache)
	dx, dw, db = affine_backward(da, fc_cache)

	return dx, dw, db

class AlexandrosNet(object):
	""" {conv-relu -> conv-relu-pool -> spatial_batchnorm ->
				affine-relu-batchnorm -> dropout -> affine -> softmax} """
	def __init__(self, input_dim=(3, 32, 32), num_filters=[32, 96], filter_size=[5, 3],
								hidden_dim=[500, 100], num_classes=10, weight_scale=1e-2, reg=0.0,
								dtype=np.float32, use_batchnorm=True, dropout=0):

		self.use_batchnorm = use_batchnorm
		self.use_dropout = dropout > 0
		self.num_layers = 5

		self.params = {}
		self.reg = reg
		self.dtype = dtype

		C, H, W = input_dim

		# Convolutional layers
		self.params['W1'] = np.random.normal(0, scale=weight_scale, size=(num_filters[0], C,
																																			filter_size[0], filter_size[0]))
		self.params['W2'] = np.random.normal(0, scale=weight_scale, size=(num_filters[1], num_filters[0],
																																				filter_size[1], filter_size[1]))
		# Fully connected layers
		self.params['W3'] = np.random.normal(0, scale=weight_scale, size=(int(num_filters[1]*H*W*0.25), hidden_dim[0]))

		# Output layer
		self.params['W5'] = np.random.normal(0, scale=weight_scale, size=(hidden_dim[0], num_classes))

		# Biases
		self.params['b1'] = np.zeros(num_filters[0])
		self.params['b2'] = np.zeros(num_filters[1])
		self.params['b3'] = np.zeros(hidden_dim[0])
		self.params['b5'] = np.zeros(num_classes)

		# Parameters
		self.params['gamma1'] = np.ones(num_filters[1])
		self.params['beta1'] = np.zeros(num_filters[1])
		self.params["gamma2"] = np.ones(hidden_dim[0])
		self.params["beta2"] = np.zeros(hidden_dim[0])
		self.params["gamma3"] = np.ones(num_classes)
		self.params["beta3"] = np.zeros(num_classes)

		self.dropout_param = {}
		if self.use_dropout:
			self.dropout_params = {'mode': 'train', 'p': dropout}

		self.bn_params = []
		if self.use_batchnorm:
			self.bn_params = [{'mode': 'train'} for i in xrange(self.num_layers - 1)]

		for k, v in self.params.iteritems():
			self.params[k] = v.astype(dtype)

	def loss(self, X, y=None):
		"""
		Evaluate loss and gradient for convolutional network.

		Input / output: Same API as TwoLayerNet in fc_net.py.
		"""
		mode = 'test' if y is None else 'train'
		if self.dropout_param is not None:
			self.dropout_param['mode'] = mode
		if self.use_batchnorm:
			for bn_param in self.bn_params:
				bn_param[mode] = mode

		W1, b1 = self.params['W1'], self.params['b1']
		W2, b2 = self.params['W2'], self.params['b2']
		W3, b3 = self.params['W3'], self.params['b3']
		W5, b5 = self.params['W5'], self.params['b5']

		gamma1, beta1 = self.params['gamma1'], self.params['beta1']
		gamma2, beta2 = self.params['gamma2'], self.params['beta2']
		gamma3, beta3 = self.params['gamma3'], self.params['beta3']

		# pass conv_param to the forward pass for the convolutional layer
		filter_size1 = W1.shape[2]
		conv_param1 = {'stride': 1, 'pad': (filter_size1 - 1) / 2}
		filter_size2 = W2.shape[2]
		conv_param2 = {'stride': 1, 'pad': (filter_size2 - 1) / 2}

		# pass pool_param to the forward pass for the max-pooling layer
		pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2}

		scores = None

		# Convolutional layers
		z1, cache1 = conv_relu_forward(X, W1, b1, conv_param1)
		z2, cache2 = conv_relu_pool_forward(z1, W2, b2, conv_param2, pool_param)
		z3, cache3 = spatial_batchnorm_forward(z2, gamma1, beta1, self.bn_params[1])

		# Fully Connected layers
		z4, cache4 = affine_relu_bn_forward(z3, W3, b3, gamma2, beta2, self.bn_params[2])
		z4, cache9 = dropout_forward(z4, self.dropout_params)

		# Output layer
		z6, cache6 = affine_forward(z4, W5, b5)
		z7, cache7 = batchnorm_forward(z6, gamma3, beta3, self.bn_params[3])
		#z8, cache8 = dropout_forward(z7, self.dropout_params)
		scores = z7

		if y is None:
			return scores

		loss, grads = 0, {}
		loss, dout = softmax_loss(scores, y)
		loss += self.reg * 0.5 * (np.power(self.params['W1'], 2).sum() +
																np.power(self.params['W2'], 2).sum() +
																np.power(self.params['W5'], 2).sum() +
																np.power(self.params['W3'], 2).sum())

		#dx8 = dropout_backward(dout, cache8)
		dx7, grads['gamma3'], grads['beta3'] = batchnorm_backward(dout, cache7)
		dx6, grads['W5'], grads['b5'] = affine_backward(dx7, cache6)
		dx6 = dropout_backward(dx6, cache9)
		dx4, grads['W3'], grads['b3'], grads['gamma2'], grads['beta2'] = affine_relu_bn_backward(dx6, cache4)

		dx3, grads['gamma1'], grads['beta1'] = spatial_batchnorm_backward(dx4, cache3)
		dx2, grads['W2'], grads['b2'] = conv_relu_pool_backward(dx3, cache2)
		dx1, grads['W1'], grads['b1'] = conv_relu_backward(dx2, cache1)

		return loss, grads


import ScreenReactive
import RainbowAll
import Bridge
import sys

def print_logo(easter_egg_on):
    """
    This function is for printing out our lovely GUI title.

    @param{bool} Want easteregg? set as true
    @returns {void}
    """
    if not easter_egg_on:
        print(" █████╗ ██╗     ██╗     ██████╗ ███████╗██████╗ ██╗██████╗ ██╗  ██╗███████╗██████╗  █████╗ ██╗     ███████╗")
        print("██╔══██╗██║     ██║     ██╔══██╗██╔════╝██╔══██╗██║██╔══██╗██║  ██║██╔════╝██╔══██╗██╔══██╗██║     ██╔════╝")
        print("███████║██║     ██║     ██████╔╝█████╗  ██████╔╝██║██████╔╝███████║█████╗  ██████╔╝███████║██║     ███████╗")
        print("██╔══██║██║     ██║     ██╔═══╝ ██╔══╝  ██╔══██╗██║██╔═══╝ ██╔══██║██╔══╝  ██╔══██╗██╔══██║██║     ╚════██║")
        print("██║  ██║███████╗███████╗██║     ███████╗██║  ██║██║██║     ██║  ██║███████╗██║  ██║██║  ██║███████╗███████║")
        print("╚═╝  ╚═╝╚══════╝╚══════╝╚═╝     ╚══════╝╚═╝  ╚═╝╚═╝╚═╝     ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚══════╝")
        print("                                                                                MacOS PythonSide Script")
        print("                                                                                By Gooday2die")
        print("                                      Please Check My Github : https://github.com/gooday2die/AllPeripherals")

    else:
        print(" ▄▄▄       ██▓     ██▓     ██▓███  ▓█████  ██▀███   ██▓ ██▓███   ██░ ██ ▓█████  ██▀███   ▄▄▄       ██▓      ██████ ")
        print("▒████▄    ▓██▒    ▓██▒    ▓██░  ██▒▓█   ▀ ▓██ ▒ ██▒▓██▒▓██░  ██▒▓██░ ██▒▓█   ▀ ▓██ ▒ ██▒▒████▄    ▓██▒    ▒██    ▒ ")
        print("▒██  ▀█▄  ▒██░    ▒██░    ▓██░ ██▓▒▒███   ▓██ ░▄█ ▒▒██▒▓██░ ██▓▒▒██▀▀██░▒███   ▓██ ░▄█ ▒▒██  ▀█▄  ▒██░    ░ ▓██▄   ")
        print("░██▄▄▄▄██ ▒██░    ▒██░    ▒██▄█▓▒ ▒▒▓█  ▄ ▒██▀▀█▄  ░██░▒██▄█▓▒ ▒░▓█ ░██ ▒▓█  ▄ ▒██▀▀█▄  ░██▄▄▄▄██ ▒██░      ▒   ██▒")
        print(" ▓█   ▓██▒░██████▒░██████▒▒██▒ ░  ░░▒████▒░██▓ ▒██▒░██░▒██▒ ░  ░░▓█▒░██▓░▒████▒░██▓ ▒██▒ ▓█   ▓██▒░██████▒▒██████▒▒")
        print(" ▒▒   ▓▒█░░ ▒░▓  ░░ ▒░▓  ░▒▓▒░ ░  ░░░ ▒░ ░░ ▒▓ ░▒▓░░▓  ▒▓▒░ ░  ░ ▒ ░░▒░▒░░ ▒░ ░░ ▒▓ ░▒▓░ ▒▒   ▓▒█░░ ▒░▓  ░▒ ▒▓▒ ▒ ░")
        print("  ▒   ▒▒ ░░ ░ ▒  ░░ ░ ▒  ░░▒ ░      ░ ░  ░  ░▒ ░ ▒░ ▒ ░░▒ ░      ▒ ░▒░ ░ ░ ░  ░  ░▒ ░ ▒░  ▒   ▒▒ ░░ ░ ▒  ░░ ░▒  ░ ░")
        print("  ░   ▒     ░ ░     ░ ░   ░░          ░     ░░   ░  ▒ ░░░        ░  ░░ ░   ░     ░░   ░   ░   ▒     ░ ░   ░  ░  ░  ")
        print("      ░  ░    ░  ░    ░  ░            ░  ░   ░      ░            ░  ░  ░   ░  ░   ░           ░  ░    ░  ░      ░  ")
        print("                                                                                MacOS PythonSide Script")
        print("                                                                                By Gooday2die")
        print("                                              Please Check My Github : https://github.com/gooday2die/AllPeripherals")

def parse_argv():
    """
    This function is for pasring argvs from system call.
    The argv call would be in this format

    python3 main.py -easteregg true -operationmode 1

    @param {void}
    @returns {list} list of argvs
    """
    argv_list = sys.argv
    return_params = list()

    positive = ['True', 'true', 'on', 'ON', 'On']
    valid_op_mode = [1, 2]

    # Operation mode 1 : Screen reactive
    # Operation mode 2 : Rainbow All
    # Others : not implemented yet...

    easter_egg_param = bool()
    operation_mode_param = int()

    if len(argv_list) < 2:  # When we do not have any params
        pass

    elif '-help' in argv_list:  # When we entered help param
        print("Please check PARAMETERS.txt in this directory")
        exit(0)

    else:  # When we have parameters
        try:
            easter_egg_index = argv_list.index("-easteregg")
            easter_egg_param = argv_list[easter_egg_index + 1] in positive

            operation_mode_index = argv_list.index("-operationmode")
            operation_mode_param = int(argv_list[operation_mode_index + 1])

            if operation_mode_param not in valid_op_mode:
                print("[ERROR] Invalid operation mode")
                exit(0)
        except:
            pass

    return_params.append(easter_egg_param)
    return_params.append(operation_mode_param)

    return return_params

def screen_reactive():
    """
    This function is for doing all the screen reactive jobs in one function
    @param {void}
    @returns {void}
    """
    bridge_obj = Bridge.Bridge(1)
    screen_reactive_obj = ScreenReactive.ScreenReactive()

    while True:
        rgb_list = screen_reactive_obj.return_rgb()
        bridge_obj.send_rgb_value(rgb_list[0], rgb_list[1], rgb_list[2])

def rainbow_all():
    """
    This function is for doing all the rainbow all jobs in one function
    @param {void}
    @returns {void}
    """
    bridge_obj = Bridge.Bridge(2)

    while True:  # This part is for error and exception detection.
        try:
            #speed = float(input("Speed (default 0.005) : "))
            speed = 0.005
            break

        except ValueError:  # if someone types 12swergw as input...
            pass

    rainbow_obj = RainbowAll.RainbowAll(bridge_obj, speed)
    rainbow_obj.rainbow_all()

if __name__ == "__main__":
    params = parse_argv()
    print(params)

    print_logo(params[0])

    if params[1] == 1:
        print("[OperationMode] Set Operation Mode 1 : Screen Reactive")
        screen_reactive()

    elif params[1] == 2:
        print("[OperationMode] Set Operation Mode 2 : Rainbow All")
        rainbow_all()

    else:  # Called this script without parmeters
        print("Please Select Operation Mode")
        print("1 ScreenReactive")
        print("2 RainbowAll")

        while True:
            try:
                op_mode = int(input("Mode : "))
                break
            except ValueError:
                pass

        if op_mode == 1:
            print("[OperationMode] Set Operation Mode 1 : Screen Reactive")
            screen_reactive()

        elif op_mode == 2:
            print("[OperationMode] Set Operation Mode 2 : Rainbow All")
            rainbow_all()

        else:
            print("[ERROR] Not implemented")
            exit(0)


from app import app
from functools import wraps
from flask import g, request, json, jsonify, abort
from app.config.Config import Config as config_app
from app.models.DefaultModel import Default as model_default
from app.decorators.ProcessResponse import process_response as _

def check_secret(f):
    @wraps(f)
    def default(*args, **kwargs):
        try:
            secret = request.headers.get('secret')
        except:
            return _(412, 'The parameter secret is empty or missing', stop = True)
        model = model_default.get_by_secret(secret)
        if model is not None:
            if config_app().data['limit'].get(model.limit, None) is None:
                return _(501, 'The requested functionality is not supported', stop = True)
        if model is not None:
            counter = model_default.get_usage(model)
            if counter >= config_app().data['limit'][model.limit]:
                return _(429, 'The usage limit has been reached', stop = True)
        else:
            return _(401, 'The secret used is not authorized', stop = True)
        return f(*args, **kwargs)
    return default

def increase_usage(f):
    @wraps(f)
    def default(*args, **kwargs):
        try:
            secret = request.headers.get('secret')
            model = model_default.get_by_secret(secret)
            model_default.update_usage(model)
        except:
            pass
        return f(*args, **kwargs)
    return default


import hlt
import logging
import time
from operator import itemgetter

game = hlt.Game("PyArmy")
logging.info("Fast and Efficient")

while True:
    game_map = game.update_map()
    StartTime = time.time()
    Xplanet = 1.6 #lower means
    Xship = 1     #More valuable
    targeted_planets = []
    command_queue = []
    AllShips = game_map._all_ships()
    AllPlanets = game_map.all_planets()
    MyShips = game_map.get_me().all_ships()
    ControlledShips = []
    for ord1 in MyShips:
        if ord1.docking_status != ord1.DockingStatus.UNDOCKED:
            continue
        ControlledShips.append(ord1)

    for ship in ControlledShips:
        if time.time() - StartTime > 1.6:
            break
        ADMIN = ship.owner
        list1 = []
        for planet in AllPlanets:
            if (planet.is_full() and planet.owner == ADMIN) or (planet.owner != ADMIN and planet.owner != None):
                continue
            list1.append([planet,ship.calculate_distance_between(planet)*Xplanet])

        list2 = []
        for enemy_ship in AllShips:
            if enemy_ship.owner == ADMIN:
                continue
            list2.append([enemy_ship,ship.calculate_distance_between(enemy_ship)*Xship])

        if list1+list2 == []:
            continue

        list3 = sorted(list1+list2,key=itemgetter(1))

        list4 = []
        for ord1 in list3:
            list4.append(ord1[0])

        for target in list4:
            if target in AllPlanets:
                if not (target in targeted_planets):
                    if ship.can_dock(target):
                        command_queue.append(ship.dock(target))
                        targeted_planets.append(target)
                    else:
                        navigate_command = ship.navigate(
                        ship.closest_point_to(target),
                        game_map,
                        speed=7)
                        if navigate_command:
                            command_queue.append(navigate_command)
                            targeted_planets.append(target)
                    break
            else:
                navigate_command = ship.navigate(
                ship.closest_point_to(target),
                game_map,
                speed=7)
                if navigate_command:
                    command_queue.append(navigate_command)
                break
        else:
            navigate_command = ship.navigate(
            ship.closest_point_to(list4[0]),
            game_map,
            speed=7)
            targeted_planets = []
            if navigate_command:
                command_queue.append(navigate_command)

    game.send_command_queue(command_queue)


import os, sys
from flask import Flask, flash, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename
from tensorflow.keras.models import load_model
import numpy as np
from PIL import Image
import tensorflow.compat.v1 as tf

app = Flask(__name__)

UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def is_allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    return redirect(url_for('predict'))

@app.route('/predict', methods=['GET', 'POST'])
def predict():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file.')
            return redirect(url_for('predict'))
        file = request.files['file']
        if file.filename == '':
            flash('No file.')
            return redirect(url_for('predict'))
        if file and is_allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)

            img = Image.open(filepath).convert('RGB')
            img = img.resize((150, 150))
            x = np.array(img, dtype=np.float32)
            x = x / 255.
            x = x.reshape((1,) + x.shape)

            graph = tf.get_default_graph()
            with graph.as_default():
                model = load_model('./model/obama_smalling_201908.h5')
                pred = model.predict(x, batch_size=1, verbose=0)
                score = pred[0][0]
                if(score >= 0.5):
                    person = 'Smalling'
                else:
                    person = 'Obama'
                    score = 1 - score

            resultmsg = '[{}] {:.4%} Sure.'.format(person, score)

            return render_template('result.html', resultmsg=resultmsg, filepath=filepath)
    return render_template('predict.html')

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)