# -*- coding: utf-8 -*-
"""
Created on Thu Jun  1 09:35:17 2017

@author: X.X
"""

import numpy as np
from scipy import constants as C
from qcodes.instrument.base import Instrument
from pycqed.measurement.waveform_control.element import Element
from pycqed.measurement.waveform_control.pulse import Pulse, CosPulse, SquarePulse, LinearPulse#, AdiabaticCosPulse
import math
from qubit import Qubit

#%%

class AdiabaticCosPulse(Pulse):

    def __init__(self, channel, name='adiabatic cos pulse', **kw):
        Pulse.__init__(self, name)

        self.channel = channel  # this is just for convenience, internally
        self.channels.append(channel)
        # this is the part the sequencer element wants to communicate with
        self.start_frequency = kw.pop('start_frequency', 1e6)
        self.end_frequency = kw.pop('end_frequency', 1e6)
        self.amplitude = kw.pop('amplitude', 0.)
        self.length = kw.pop('length', 0.)
        self.phase = kw.pop('phase', 0.)

    def __call__(self, **kw):
        self.start_frequency = kw.pop('start_frequency', self.start_frequency)
        self.end_frequency = kw.pop('end_frequency', self.end_frequency)
        self.amplitude = kw.pop('amplitude', self.amplitude)
        self.length = kw.pop('length', self.length)
        self.phase = kw.pop('phase', self.phase)

        return self

    def chan_wf(self, chan, tvals):
        self.frequency = np.linspace(self.start_frequency, self.end_frequency, len(tvals))
        return self.amplitude * np.cos(2 * np.pi *
                                       (self.frequency * tvals +
                                        self.phase / 360.))

#%% gate

class Gate:

    def __init__(self, name, **kw):

        self.name = name                                 ## name of a gate, e.g. 'X_Q1' 'CZ_Q12'
        self.qubit = kw.pop('qubit', None)
        self.control_qubit = kw.pop('control_qubit', None)
        self.target_qubit = kw.pop('target_qubit', None)
        self.qubit_name = 'qubit'

##      Gates will be an object that consists all the pulse information in the operation,
##      but it will just store the pulses in information and the links in time domain
##      between different pulses, but not adding it into an Element

#%% single qubit gate

class Single_Qubit_Gate(Gate):

    def __init__(self, name, qubit, rotating_axis = [1, 0, 0], amplitude = None, frequency_shift = 0, refphase = 0, IQ_phase = 0):
        super().__init__(name,)

        self.qubit = qubit.name
        self.amplitude = qubit.IQ_amplitude if amplitude == None else amplitude
#        self.frequency_shift = qubit.frequency if frequency == None else frequency
        self.frequency_shift = frequency_shift
        self.channel_I = qubit.microwave_gate['channel_I']
        self.channel_Q = qubit.microwave_gate['channel_Q']
        self.channel_PM = qubit.microwave_gate['channel_PM']
        self.channel_FM = qubit.microwave_gate['channel_FM']
        self.channel_VP = qubit.plunger_gate['channel_VP']

        self.Pi_pulse_length = qubit.Pi_pulse_length
        self.halfPi_pulse_length = qubit.halfPi_pulse_length

        self.PM_before = 40e-9
        self.PM_after = 2e-9
        '''
        for cbox testing
        '''
#        self.PM_before = 500e-9
#        self.PM_after = 500e-9
        '''
        end
        '''

        self.voltage_pulse_length = 0

        self.refphase = refphase*C.pi/180
        self.IQ_phase = IQ_phase
        self.axis = np.array(rotating_axis)
#        if self.axis[0]!= 0:
#            self.axis_angle = np.arctan(self.axis[1]/self.axis[0])
#        else :
        self.axis_angle = np.arctan2(self.axis[1],self.axis[0])

        self.pulses = [None, None, None, None]            ## [microwave1_I, microwave1_Q, voltage, microwave2_I, microwave2_Q]

    def XY_rotation(self, degree = 90, length = None, waiting_time = 0, refgate = None, refpoint = 'end',
                    refqubit = None):
#        global phase
#        IQ_Modulation = self.frequency
        if length is not None:
            pulse_length = length
        else:
            pulse_length = self.halfPi_pulse_length if degree == 90 else degree*self.Pi_pulse_length/180

        pulse_amp = self.amplitude

        pulse_delay = Instrument.find_instrument(self.qubit).pulse_delay
        if self.qubit == 'qubit_2' and refqubit == 'qubit_2':
            pulse_delay = 0

        ## voltage pulse is not used here
        voltage_pulse = SquarePulse(channel = self.channel_VP, name = '%s_voltage_pulse'%self.name,
                                    amplitude = 0, length = 0)#pulse_length + waiting_time)

        PM_pulse = SquarePulse(channel = self.channel_PM, name = '%s_PM_pulse'%self.name,
                               amplitude = 2, length = pulse_length+self.PM_before+self.PM_after)

        if self.frequency_shift == 0:
            microwave_pulse_I = SquarePulse(channel = self.channel_I, name = '%s_microwave_pulse_I'%self.name,
                                            amplitude = pulse_amp*np.cos(-self.refphase + self.axis_angle),
                                            length = pulse_length)

            microwave_pulse_Q = SquarePulse(channel = self.channel_Q, name = '%s_microwave_pulse_Q'%self.name,
                                            amplitude = pulse_amp*np.sin(-self.refphase + self.axis_angle),
                                            length = pulse_length)

        elif self.frequency_shift != 0: ##here frequency and phase is not yet ready!!!!!!!!!!!
            phase = self.IQ_phase-self.refphase + self.axis_angle
            freq = self.frequency_shift
            microwave_pulse_I = CosPulse(channel = self.channel_I, name = '%s_microwave_pulse_I'%self.name, frequency = freq,
                                         amplitude = pulse_amp,
                                         length = pulse_length, phase = phase)

            microwave_pulse_Q = CosPulse(channel = self.channel_Q, name = '%s_microwave_pulse_Q'%self.name, frequency = freq,
                                         amplitude = pulse_amp,
                                         length = pulse_length, phase = phase-90)

        '''
        adiabatic sweep for test
        '''
        if type(self.frequency_shift) is list :
            phase = self.IQ_phase-self.refphase + self.axis_angle
            freq = self.frequency_shift
            start_freq = self.frequency_shift[0]
            end_freq = self.frequency_shift[1]

            microwave_pulse_I = AdiabaticCosPulse(channel = self.channel_I, name = '%s_microwave_pulse_I'%self.name,
                                                  start_frequency = start_freq, end_frequency = end_freq,
                                                  amplitude = pulse_amp,
                                                  length = pulse_length, phase = phase)

            microwave_pulse_Q = AdiabaticCosPulse(channel = self.channel_Q, name = '%s_microwave_pulse_Q'%self.name,
                                                  start_frequency = start_freq, end_frequency = end_freq,
                                                  amplitude = pulse_amp,
                                                  length = pulse_length, phase = phase-90)

        '''
        '''

        self.pulses[0] = {
                'pulse': voltage_pulse,
                'pulse_name': voltage_pulse.name,
                'refpulse': None if refgate == None else refgate[0]['pulse_name'],
                'refpoint': refpoint,
                'waiting': 0
                }

        self.pulses[1] = {
                'pulse': microwave_pulse_I,
                'pulse_name': microwave_pulse_I.name,
                'refpulse': None if refgate == None else refgate[-2]['pulse_name'],                   ## name of the refpulse
                'refpoint': refpoint,
                'waiting': waiting_time + pulse_delay
                }

        self.pulses[2] = {
                'pulse': microwave_pulse_Q,
                'pulse_name': microwave_pulse_Q.name,
                'refpulse': '%s_microwave_pulse_I'%self.name,
                'refpoint': 'start',
                'waiting': 0
                }
        ##  here you just construct a dictionary which contains all the information of pulses you use
        self.pulses[3] = {
                'pulse': PM_pulse,
                'pulse_name': PM_pulse.name,
                'refpulse': '%s_microwave_pulse_I'%self.name,
                'refpoint': 'start',
                'waiting': -self.PM_before
                }

        return True

    def Z_rotation(self, degree, name = 'Z_rotation', refphase = 0, waiting_time = 0, refrotation = None):
#        global refphase
#        refphase += degree
        return True

#    def Arbitrary_rotation(self, degree, rotating_axis = [1,0,0]):
#        theta = np.arccos(rotating_axis[2])
#        phi = np.arccos(rotating_axis[0]/np.sin(theta))
#        self.Z_rotation(degree = -phi, name = 'step1')
#        self.Y_rotation(degree = -theta, name = 'step2', refrotation = 'step1')
#        self.Z_rotation(degree = degree, name = 'step3', refrotation = 'step2')
#        self.Y_rotation(degree = theta, name = 'step4', refrotation = 'step3')
#        self.Z_rotation(degree = phi, refrotation = 'step4')
#        return True

#%% twp qubit gate

class Two_Qubit_Gate(Gate):

    def __init__(self, name, control_qubit, target_qubit, refphase = 0,):

        super().__init__(name,)

        self.control_qubit = control_qubit
        self.target_qubit = target_qubit

        """
        the three parameters below are very important,
        """
        self.frequency = target_qubit.frequency
        self.refphase = refphase
        self.Pi_pulse_length = target_qubit.Pi_pulse_length

        self.detuning_amplitude_C = 0.15
        self.detuning_amplitude_T = -0.1

        self.detuning_length_Pi = 10e-6
        self.channel_VP1 = control_qubit.plunger_gate['channel_VP']
        self.channel_VP2 = target_qubit.plunger_gate['channel_VP']
        self.channel_I = target_qubit.microwave_gate['channel_I']
        self.channel_Q = target_qubit.microwave_gate['channel_Q']

        self.channel_FM = target_qubit.microwave_gate['channel_FM']
        self.channel_PM = target_qubit.microwave_gate['channel_PM']

        self.pulses = []

    def CRotation_gate(self, exchanging_time, refgate):
        self.detuning(refpulse = refgate[-1]['pulse_name'])

        self.X_Pi_gate(refpulse = self.pulses[-1]['pulse_name'])

        return True

    def CPhase_gate(self, name = 'CPhase_gate', rotating_phase = 180, refgate = None, waiting_time = 0):

        length = rotating_phase*self.detuning_length_Pi/180

        self.detuning(name = name, length = length,
                       waiting_time = waiting_time, refpulse = None if refgate == None else refgate[-1]['pulse_name'])
        return True

    def CNot_gate(self, exchanging_time, delay_time, refgate):
        self.X_gate(refpulse = refgate[-1]['pulse_name'])
        self.CPhase_gate(refpulse = self.pulses[-1]['pulse_name'])
        self.X_gate(refpulse = self.pulses[-1]['pulse_name'])
        return True

    def detuning(self, name = 'detuning_pulse', length = 0,
                 waiting_time = 0, refpulse = None, refpoint = 'end', **kw):

        AMP_C = kw.pop('amplitude_control', self.detuning_amplitude_C)
        AMP_T = kw.pop('amplitude_target', self.detuning_amplitude_T)

        voltage_pulse_C = SquarePulse(channel = self.channel_VP1, name = '%s_detuning_pulse_C'%self.name,
                                       amplitude = AMP_C, length = length,
                                       refpulse = refpulse)

        voltage_pulse_T = SquarePulse(channel = self.channel_VP2, name = '%s_detuning_pulse_T'%self.name,
                                       amplitude = AMP_T, length = length,
                                       refpulse = refpulse)

        detuning_pulse_C = {
                'pulse': voltage_pulse_C,
                'pulse_name': voltage_pulse_C.name,
                'refpulse': None if refpulse == None else refpulse,
                'refpoint': refpoint,
                'waiting': waiting_time
                }

        detuning_pulse_T = {
                'pulse': voltage_pulse_T,
                'pulse_name': voltage_pulse_T.name,
                'refpulse': '%s_detuning_pulse_C'%self.name,
                'refpoint': 'start',
                'waiting': 0
                }

        self.pulses.append(detuning_pulse_C)
        self.pulses.append(detuning_pulse_T)

        return True

    def ramp(self, name = 'ramp_pulse', length = 0, ramp = 'up',
             waiting_time = 0, refpulse = None, refpoint = 'end', **kw):

        AMP_C = kw.pop('amplitude_control', self.detuning_amplitude_C)
        AMP_T = kw.pop('amplitude_target', self.detuning_amplitude_T)

        if ramp == 'up':
            start_C = 0
            end_C = AMP_C
            start_T = 0
            end_T = AMP_T

        elif ramp == 'down':
            start_C = AMP_C
            end_C = 0
            start_T = AMP_T
            end_T = 0

        else:
            raise NameError('ramp direction unknown: ', ramp)

        voltage_pulse_C = LinearPulse(channel = self.channel_VP1, name = '%s_detuning_pulse_C'%self.name,
                                       start_value = start_C, end_value = end_C, length = length,
                                       refpulse = refpulse)

        voltage_pulse_T = LinearPulse(channel = self.channel_VP2, name = '%s_detuning_pulse_T'%self.name,
                                       start_value = start_T, end_value = end_T, length = length,
                                       refpulse = refpulse)

        detuning_pulse_C = {
                'pulse': voltage_pulse_C,
                'pulse_name': voltage_pulse_C.name,
                'refpulse': None if refpulse == None else refpulse,
                'refpoint': refpoint,
                'waiting': waiting_time
                }

        detuning_pulse_T = {
                'pulse': voltage_pulse_T,
                'pulse_name': voltage_pulse_T.name,
                'refpulse': '%s_detuning_pulse_C'%self.name,
                'refpoint': 'start',
                'waiting': 0
                }

        self.pulses.append(detuning_pulse_C)
        self.pulses.append(detuning_pulse_T)

        return True

    def XY_rotation(self, name, degree = 90, waiting_time = 0, refpulse = None, refpoint = 'end'):

        microwave_pulse_I = SquarePulse(channel = self.channel_I, name = '%s_microwave_pulse_I'%name,
                   amplitude = np.cos(self.refphase), length = degree*self.Pi_pulse_length/180)

        microwave_pulse_Q = SquarePulse(channel = self.channel_Q, name = '%s_microwave_pulse_Q'%name,
                   amplitude = np.sin(self.refphase), length = degree*self.Pi_pulse_length/180)

        component_I = {
                'pulse': microwave_pulse_I,
                'pulse_name': microwave_pulse_I.name,
                'refpulse': refpulse,                   ## name of the refpulse
                'refpoint': refpoint,
                'waiting': waiting_time
                }

        component_Q = {
                'pulse': microwave_pulse_Q,
                'pulse_name': microwave_pulse_Q.name,
                'refpulse': '%s_microwave_pulse_I'%name,
                'refpoint': 'start',
                'waiting': 0
                }

        self.pulses.append(component_I)
        self.pulses.append(component_Q)

    def X_gate(self, name = 'X_halfPi', waiting_time = 0, refpulse = None, refpoint = 'end'):

        self.XY_rotation(name = name, degree = 90, waiting_time = waiting_time, refpulse = refpulse, refpoint = refpoint)

        return 0

    def X_Pi_gate(self, name = 'X_Pi', waiting_time = 0, refpulse = None, refpoint = 'end'):

        self.XY_rotation(name = name, degree = 180, waiting_time = waiting_time, refpulse = refpulse, refpoint = refpoint)

        return 0

    def Y_gate(self, name = 'Y_halfPi', waiting_time = 0, refpulse = None, refpoint = 'end'):

        self.XY_rotation(name = name, degree = 90, waiting_time = waiting_time, refpulse = refpulse, refpoint = refpoint)

        return 0

    def Y_Pi_gate(self, name = 'Y_Pi', waiting_time = 0, refpulse = None, refpoint = 'end'):

        self.XY_rotation(name = name, degree = 180, waiting_time = waiting_time, refpulse = refpulse, refpoint = refpoint)

        return 0

class CPhase_Gate(Two_Qubit_Gate):

    def __init__(self, name = 'CPhase_gate', control_qubit = None, target_qubit = None,
                 amplitude_control = 0, amplitude_target = 0, length = 0,
                 rotating_phase = 180, refgate = None, refpoint = 'end', waiting_time = 0):

        super().__init__(name, control_qubit, target_qubit)

        pulse_length = length if length != 0 else rotating_phase*self.detuning_length_Pi/180

        self.detuning(name = name, length = pulse_length, waiting_time = waiting_time, refpoint = refpoint,
                      amplitude_control = amplitude_control, amplitude_target = amplitude_target,
                      refpulse = None if refgate == None else refgate[-2]['pulse_name'])

    def __call__(self, **kw):

        return self

class Ramp(Two_Qubit_Gate):

    def __init__(self, name = 'Ramp', control_qubit = None, target_qubit = None,
                 amplitude_control = 0, amplitude_target = 0, length = 0, ramp = 'up',
                 rotating_phase = 180, refgate = None, refpoint = 'end', waiting_time = 0):

        super().__init__(name, control_qubit, target_qubit)

        pulse_length = length if length != 0 else rotating_phase*self.detuning_length_Pi/180

        self.ramp(name = name, length = pulse_length, waiting_time = waiting_time, refpoint = refpoint,
                  amplitude_control = amplitude_control, amplitude_target = amplitude_target, ramp = ramp,
                  refpulse = None if refgate == None else refgate[-2]['pulse_name'])

    def __call__(self, **kw):

        return self

class CNot_Gate(Two_Qubit_Gate):

    def __init__(self, name = 'CPhase_gate', control_qubit = None, target_qubit = None,
                 rotating_phase = 180, refgate = None, refpoint = 'end', waiting_time = 0):

        super().__init__(name, control_qubit, target_qubit)

        length = rotating_phase*self.detuning_length_Pi/180

        self.X_gate(name = name + '_X1', waiting_time = waiting_time, refpoint = refpoint,
                    refpulse = None if refgate == None else refgate[-2]['pulse_name'])

        self.detuning(name = name+'_detuning', length = length, waiting_time = 1e-6,
                      refpulse = self.pulses[-1]['pulse_name'])

        self.X_gate(name = name+'_X2', waiting_time = 1e-6, refpulse = self.pulses[-1]['pulse_name'])

    def __call__(self, **kw):

        return self

class CRotation_Gate(Two_Qubit_Gate):

    def __init__(self, name = 'CPhase_gate', control_qubit = None, target_qubit = None,
                 rotating_phase = 180, refgate = None, refpoint = 'end', waiting_time = 0):

        super().__init__(name, control_qubit, target_qubit)

        length = rotating_phase*self.detuning_length_Pi/180

        self.detuning(name = name+'_detuning', length = length, waiting_time = waiting_time, refpoint = refpoint,
                      refpulse = None if refgate == None else refgate[-2]['pulse_name'])

        self.X_Pi_gate(name = name+'_X', refpulse = self.pulses[-1]['pulse_name'], refpoint = 'center', waiting_time = 2e-6)


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

"""The setup script."""

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
]

test_requirements = [
    'coverage',
    'flake8',
    'manuel',
    'mock',
    'pytest',
    'pytest-cov',
    'pytest-flake8',
    'pytest-sugar',
]

doc_requirements = [
    'sphinx',
    'sphinx-autobuild',
    'sphinx_rtd_theme',
    'sphinxcontrib-napoleon',
]

dev_requirements = [
    'bumpversion',
    'ipdb',
    'ipython',
    'twine',
    'wheel',
] + test_requirements + doc_requirements

setup(
    author="Tony S Yu",
    author_email='tsyu80@gmail.com',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ],
    description="Logging utilities to help you over-communicate",
    install_requires=requirements,
    license="MIT license",
    long_description=readme + '\n\n' + history,
    include_package_data=True,
    keywords='logquacious',
    name='logquacious',
    packages=find_packages(include=['logquacious']),
    tests_require=test_requirements,
    extras_require={
        'dev': dev_requirements,
        'docs': doc_requirements,
    },
    url='https://github.com/tonysyu/logquacious',
    version='0.5.0',
    zip_safe=False,
)


import joblib
import pandas as pd
from shiny import ui
from _utils import *

__all__ = ["user_input_select",
           "output_model"]

MODEL_PATH = 'model/nn_model.joblib'
NORM_PATH = 'model/normalization.joblib'

model = joblib.load(MODEL_PATH)
normalizer = joblib.load(NORM_PATH)

def user_input_select():
    return ui.panel_sidebar(ui.input_slider("age", "AGE", min=age["min"], max=age["max"], value=age["value"]),
                            ui.input_select("workclass", "WORKCLASS", workclass),
                            ui.input_select("education", "EDUCATION", education),
                            ui.input_radio_buttons("marital_status", "MARITAL STATUS", marital_status),
                            ui.input_select("occupation", "OCCUPATION", occupation),
                            ui.input_select("relationship", "RELATIONSHIP", relationship),
                            ui.input_radio_buttons("race", "RACE", race),
                            ui.input_select("gender", "GENDER", gender),
                            ui.input_numeric("capital_gain", "CAPTITAL GAIN",
                                             cap_gain["value"], min=cap_gain["min"], max=cap_gain["max"]),
                            ui.input_numeric("capital_loss", "CAPTITAL LOSS",
                                             cap_loss["value"], min=cap_loss["min"], max=cap_loss["max"]),
                            ui.input_numeric("hours_week", "HOURS PER WEEK",
                                             hp_week["value"], min=hp_week["min"], max=hp_week["max"]),
                            ui.input_select("native_country", "NATIVE_COUNTRY", native_country),
                            ui.input_action_button("btn", "INCOME?", class_="btn-success")
                            )

def output_model(df: pd.DataFrame):

    # convert to dummy variables
    category_columns = list(df.select_dtypes(include=['category', 'object']).columns)
    other_columns = list(df.select_dtypes(exclude=['category', 'object']).columns)

    df_dummy = pd.get_dummies(df[category_columns], drop_first=False, dtype=float)

    df_num = df[other_columns]
    df = pd.concat([df_num, df_dummy], axis=1)
    del df_dummy, df_num

    # all columns - add other of dummy features
    train_columns = list(normalizer.feature_names_in_)
    add_col = [col for col in train_columns if col not in df.columns]

    for col in add_col:
        df[col] = 0  # se incluye con valor a cero

    df = df[train_columns]  # la muestra a predecir con el mismo orden que la muestra de entrenamiento

    # normalize variables
    X = normalizer.transform(df)

    # getting prediction
    # redes convolucionales - se añade una dimensión a los datos
    X = X.reshape(X.shape[0], X.shape[1], 1)
    prediction_proba = model.predict(X)

    output1 = round(prediction_proba[0][0] * 100, 2)
    pred = f"{str(output1)} %"
    return pred


from aws_cdk import (
    aws_ec2 as ec2,
    aws_iam as iam,
    core,
)

class TestInstanceStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, vpc: ec2.Vpc, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Set the AMI to the latest Amazon Linux 2
        amazon_linux_2_ami = ec2.MachineImage.latest_amazon_linux(
            generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
            edition=ec2.AmazonLinuxEdition.STANDARD,
            virtualization=ec2.AmazonLinuxVirt.HVM,
            storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
        )

        # Create a role for the instance and attach the SSM Managed Policy to this role.
        instance_role = iam.Role(self, "test-instance-SSM-role",
            assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
        )

        instance_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonEC2RoleforSSM"))

        # Create a test instance in any available private subnet allowing all outbound connections. No inbound connections allowed.
        instance = ec2.Instance(self, "test-instance",
            instance_type=ec2.InstanceType("t3.nano"),
            machine_image=amazon_linux_2_ami,
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.ISOLATED
            ),
            role=instance_role,
            allow_all_outbound=True
            )

        core.CfnOutput(self, "output-instance-id",
                       value=instance.instance_id)


#!/usr/bin/python3
"""
Pings a To-Do API for data and displays tasks completed
and tasks done for a specified user
"""
import requests
from sys import argv

if __name__ == '__main__':
    user_id = argv[1]
    user = requests.get("https://jsonplaceholder.typicode.com/users/{}".
                        format(user_id), verify=False).json()
    todo = requests.get("https://jsonplaceholder.typicode.com/todos?userId={}".
                        format(user_id), verify=False).json()

    completed_tasks = []
    for task in todo:
        if task.get('completed') is True:
            completed_tasks.append(task.get('title'))
    print("Employee {} is done with tasks({}/{}):"
          .format(user.get('name'), len(completed_tasks), len(todo)))

    for task in completed_tasks:
        print("\t {}".format(task))


#Напишите фрагмент кода, который создает словарь для хранения имени учащегося,
# оценок учащегося за задания, оценок учащегося за лабораторные работы и оценок учащегося за тесты

try:
    # создаем пустой словарь для хранения информации об учащемся
    student = {}

    # получение имени учащегося
    student['name'] = input("Введите имя учащегося: ")

    # получение оценок за задания в виде списка
    score_assignment = input("Введите оценки за задания: ")
    student['assignments'] = [int(score) for score in score_assignment.split(',')]

    # получение оценок за лабораторные работы в виде списка
    score_lab= input("Введите оценки за лабораторные работы: ")
    student['labs'] = [float(score) for score in score_lab.split(',')]

    # получение оценок за тесты в виде списка
    score_test = input("Введите оценки за тесты : ")
    student['tests'] = [int(score) for score in score_test.split(',')]

    # выводим словарь  с информацией об учащемся
    print("Информация об учащемся:", student)

except ValueError:
    print("Ввод неверный")


"""
Logging utilities, adapted from tf_logging
"""

# pylint: disable=unused-import
# pylint: disable=g-bad-import-order
# pylint: disable=invalid-name
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging as _logging
import os as _os
import re
import sys as _sys
import traceback as _traceback
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import WARN

_name2level = {
    'FATAL': FATAL,
    'F': FATAL,

    'ERROR': ERROR,
    'ERR': ERROR,
    'E': ERROR,

    'WARNING': WARN,
    'WARN': WARN,
    'W': WARN,

    'INFO': INFO,
    'I': INFO,

    'DEBUG': DEBUG,
    'D': DEBUG,
}

def _init_log_level():
    pkg = __name__.split('.')[0]
    env_key = pkg.upper() + '_LOG_LEVEL'
    for k, v in _os.environ.items():
        if k.upper() == env_key:
            if v.upper() in _name2level.keys():
                return _name2level[v.upper()]
            elif re.match(r'^\d$', v):
                return int(v)
            else:
                print(f'Unrecognized log level {v}.', file=_sys.stderr)

    _dev_mode = __file__.lower().find('site-packages') < 0
    return INFO if _dev_mode else WARN

# settings
_log_level = _init_log_level()

# _log_format = '%(name)s %(levelname).1s%(asctime)s.%(msecs)d %(filename)s %(lineno)d - %(message)s'
# _log_format = '%(module)s %(levelname).1s %(filename)s %(lineno)d - %(message)s'
# _log_format = '%(levelname).1s %(sname)s.%(filename)s %(lineno)d - %(message)s'
_log_format = '%(asctime)s %(levelname).1s %(sname)s.%(filename)s %(lineno)d - %(message)s'

# _DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
_date_format = '%m-%d %H:%M:%S'

# # detect code run in interactive mode or not
# _interactive = False
# try:
#     # This is only defined in interactive shells.
#     if _sys.ps1: _interactive = True
# except AttributeError:
#     # Even now, we may be in an interactive shell with `python -i`.
#     _interactive = _sys.flags.interactive

class CustomizedLogFormatter(_logging.Formatter):

    def __init__(self, fmt=None, datefmt=None, style='%'):
        super(CustomizedLogFormatter, self).__init__(fmt, datefmt, style)

        self.with_simple_name = fmt.find(style + '(sname)') >= 0

    def formatMessage(self, record):
        if self.with_simple_name:
            record.sname = self.get_simple_name(record.name)

        if isinstance(record.msg, Exception):
            ex = record.msg
            lines = _traceback.format_exception(type(ex), ex, ex.__traceback__)
            record.message = lines[-1] + ''.join(lines[:-1])

        return super(CustomizedLogFormatter, self).formatMessage(record)

    @staticmethod
    def get_simple_name(name):
        if name.endswith('@'):
            return name

        sa = name.split('.')
        if len(sa) <= 1:
            return name

        names = [sa[0]] + \
                [sa[i][0] for i in range(1, len(sa) - 1)]
        return '.'.join(names)

class CustomizedLogger(_logging.Logger):
    FATAL = FATAL
    ERROR = ERROR
    INFO = INFO
    DEBUG = DEBUG
    WARN = WARN

    def __init__(self, name, level=_log_level) -> None:
        super(CustomizedLogger, self).__init__(name, level)

        self.findCaller = _logger_find_caller
        self.setLevel(_log_level)
        self.propagate = False  # disable propagate to parent

        # Don't further configure the logger if the root logger is
        # already configured. This prevents double logging in those cases.
        if not self.handlers:
            # # Add the output handler.
            # stream = _sys.stdout if _interactive else _sys.stderr
            # handler = _logging.StreamHandler(stream)
            # handler.setFormatter(CustomizedLogFormatter(_log_format, _date_format))
            # self.addHandler(handler)

            stdout_handler = _logging.StreamHandler(_sys.stdout)
            stdout_handler.setFormatter(CustomizedLogFormatter(_log_format, _date_format))
            stdout_handler.addFilter(lambda rec: rec.levelno < WARN)
            self.addHandler(stdout_handler)

            stderr_handler = _logging.StreamHandler(_sys.stderr)
            stderr_handler.setFormatter(CustomizedLogFormatter(_log_format, _date_format))
            stderr_handler.addFilter(lambda rec: rec.levelno >= WARN)
            self.addHandler(stderr_handler)

    def getEffectiveLevel(self):
        return _log_level

    def log(self, level, msg, *args, **kwargs):
        super(CustomizedLogger, self).log(level, msg, *args, **kwargs)

    def fatal(self, msg, *args, **kwargs):
        self.log(FATAL, msg, *args, **kwargs)
        self.exception()

    def error(self, msg, *args, **kwargs):
        self.log(ERROR, msg, *args, **kwargs)

    def warning(self, msg, *args, **kwargs):
        self.log(WARN, msg, *args, **kwargs)

    def warn(self, msg, *args, **kwargs):
        self.log(WARN, msg, *args, **kwargs)

    def info(self, msg, *args, **kwargs):
        self.log(INFO, msg, *args, **kwargs)

    def debug(self, msg, *args, **kwargs):
        self.log(DEBUG, msg, *args, **kwargs)

    def log_if(self, level, msg, condition, *args):
        """Log 'msg % args' at level 'level' only if condition is fulfilled."""
        if callable(condition):
            if condition():
                self.log(level, msg, *args)
        elif condition:
            self.log(level, msg, *args)

    def log_every_n(self, level, msg, n, *args):
        """Log 'msg % args' at level 'level' once per 'n' times.

        Logs the 1st call, (N+1)st call, (2N+1)st call,  etc.
        Not threadsafe.

        Args:
          level: The level at which to log.
          msg: The message to be logged.
          n: The number of times this should be called before it is logged.
          *args: The args to be substituted into the msg.
        """
        count = _get_next_log_count_per_token(_get_file_and_line())
        self.log_if(level, msg, not (count % n), *args)

    def log_first_n(self, level, msg, n, *args):  # pylint: disable=g-bad-name
        """Log 'msg % args' at level 'level' only first 'n' times.

        Not threadsafe.

        Args:
          level: The level at which to log.
          msg: The message to be logged.
          n: The number of times this should be called before it is logged.
          *args: The args to be substituted into the msg.
        """
        count = _get_next_log_count_per_token(_get_file_and_line())
        self.log_if(level, msg, count < n, *args)

    def is_debug_enabled(self):
        return self.isEnabledFor(DEBUG)

    def is_info_enabled(self):
        return self.isEnabledFor(INFO)

    def is_warning_enabled(self):
        return self.isEnabledFor(WARN)

    def is_enabled_for(self, level):
        return self.isEnabledFor(level)

    def isEnabledFor(self, level):
        if self.disabled:
            return False

        return level >= self.getEffectiveLevel()

def get_logger(name):
    original_logger_class = _logging.getLoggerClass()
    _logging.setLoggerClass(CustomizedLogger)
    logger = _logging.getLogger(name)
    _logging.setLoggerClass(original_logger_class)

    return logger

# compatible with pylog
def getLogger(name):
    return get_logger(name)

def get_level():
    """Return how much logging output will be produced for newer logger."""
    return _log_level

def set_level(v):
    """Sets newer logger threshold for what messages will be logged."""
    assert isinstance(v, (str, int))

    global _log_level

    _log_level = to_level(v)

def to_level(v):
    assert isinstance(v, (int, str)) or v is None

    if v is None:
        v = _log_level
    elif isinstance(v, str):
        if v.upper() in _name2level.keys():
            v = _name2level[v.upper()]
        elif re.match(r'^\d$', v):
            v = int(v)
        else:
            raise ValueError(f'Unrecognized log level {v}.')

    return v

def _get_caller(offset=3):
    """Returns a code and frame object for the lowest non-logging stack frame."""
    # Use sys._getframe().  This avoids creating a traceback object.
    # pylint: disable=protected-access
    f = _sys._getframe(offset)
    # pylint: enable=protected-access
    our_file = f.f_code.co_filename
    f = f.f_back
    while f:
        code = f.f_code
        if code.co_filename != our_file:
            return code, f
        f = f.f_back
    return None, None

_logger_caller_offset = 4

# The definition of `findCaller` changed in Python 3.2,
# and further changed in Python 3.8
if _sys.version_info.major >= 3 and _sys.version_info.minor >= 8:
    def _logger_find_caller(stack_info=False, stacklevel=1, caller_offset=_logger_caller_offset):
        code, frame = _get_caller(caller_offset)
        sinfo = None
        if stack_info:
            sinfo = '\n'.join(_traceback.format_stack())
        if code:
            return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
        else:
            return '(unknown file)', 0, '(unknown function)', sinfo
elif _sys.version_info.major >= 3 and _sys.version_info.minor >= 2:

    def _logger_find_caller(stack_info=False, caller_offset=_logger_caller_offset):
        code, frame = _get_caller(caller_offset)
        sinfo = None
        if stack_info:
            sinfo = '\n'.join(_traceback.format_stack())
        if code:
            return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
        else:
            return '(unknown file)', 0, '(unknown function)', sinfo
else:
    def _logger_find_caller(caller_offset=_logger_caller_offset):
        code, frame = _get_caller(caller_offset)
        if code:
            return (code.co_filename, frame.f_lineno, code.co_name)
        else:
            return '(unknown file)', 0, '(unknown function)'

# Counter to keep track of number of log entries per token.
_log_counter_per_token = {}

def _get_next_log_count_per_token(token):
    """Wrapper for _log_counter_per_token.

    Args:
      token: The token for which to look up the count.

    Returns:
      The number of times this function has been called with
      *token* as an argument (starting at 0)
    """
    global _log_counter_per_token  # pylint: disable=global-variable-not-assigned
    _log_counter_per_token[token] = 1 + _log_counter_per_token.get(token, -1)
    return _log_counter_per_token[token]

def _get_file_and_line():
    """Returns (filename, linenumber) for the stack frame."""
    code, f = _get_caller()
    if not code:
        return '<unknown>', 0
    return code.co_filename, f.f_lineno


"""
Determine result of Trouble Sort.

:param v: list of numbers to sort.
:return: index of sorting error, or -1 if list will be sorted.
"""
def trouble_sort_predictor(v):
  # Trouble sort is essentially bubble sorts on two interleaved lists.
  # List 1 is all the even elements.
  # List 2 is all the odd elements.
  # So let's separate out the two lists, sort them independently
  # (using something efficient like Python's built in sort(), and work out
  # whether there will be an error.
  v_even = v[0::2]
  v_odd = v[1::2]
  v_even.sort()
  v_odd.sort()
  # Note that len(v_even) always >= len(v_odd)
  for i in range(len(v_even)):
    # Compare with odd behind.
    if i > 0:
      if v_odd[i-1] > v_even[i]:
        return 2 * i - 1

    # Compare with odd ahead.
    if i >= len(v_odd):
      # Reached end of list.
      break
    elif v_even[i] > v_odd[i]:
      return 2 * i

  return -1

def main():
  num_tests = int(input())
  for i in range(1, num_tests+1):
    n = input()
    v = list(map(int, input().split()))
    result = trouble_sort_predictor(v)
    result_str = str(result)
    if result == -1:
      result_str = "OK"
    print("Case #{:d}: {:s}".format(i, result_str))

if __name__ == "__main__":
    main()


"""
Author: Isabella Liu 4/28/21
Feature: Hourglass and PSMNet (stacked hourglass) module
"""

import math

from .psmnet_submodule_ray import *
from torch.autograd import Variable

class hourglass(nn.Module):
    def __init__(self, inplanes):
        super(hourglass, self).__init__()

        self.conv1 = nn.Sequential(
            convbn_3d(inplanes, inplanes * 2, kernel_size=3, stride=2, pad=1),
            nn.ReLU(inplace=True)
        )

        self.conv2 = convbn_3d(inplanes * 2, inplanes * 2, kernel_size=3, stride=1, pad=1)

        self.conv3 = nn.Sequential(
            convbn_3d(inplanes * 2, inplanes * 2, kernel_size=3, stride=2, pad=1),
            nn.ReLU(inplace=True)
        )

        self.conv4 = nn.Sequential(
            convbn_3d(inplanes * 2, inplanes * 2, kernel_size=3, stride=1, pad=1),
            nn.ReLU(inplace=True)
        )

        self.conv5 = nn.Sequential(
            nn.ConvTranspose3d(inplanes * 2, inplanes * 2, kernel_size=3, padding=1, output_padding=1, stride=2,
                               bias=False),
            nn.BatchNorm3d(inplanes * 2)
        )

        self.conv6 = nn.Sequential(
            nn.ConvTranspose3d(inplanes * 2, inplanes, kernel_size=3, padding=1, output_padding=1, stride=2,
                               bias=False),
            nn.BatchNorm3d(inplanes)
        )

    def forward(self, x, presqu, postqu):
        out = self.conv1(x)
        pre = self.conv2(out)
        if postqu is not None:
            pre = F.relu(pre + postqu, inplace=True)
        else:
            pre = F.relu(pre, inplace=True)

        out = self.conv3(pre)
        out = self.conv4(out)

        if presqu is not None:
            post = F.relu(self.conv5(out) + presqu, inplace=True)
        else:
            post = F.relu(self.conv5(out) + pre, inplace=True)

        out = self.conv6(post)
        return out, pre, post

class ConvBnReLU3D(nn.Module):
    def __init__(self, in_channels, out_channels,
                 kernel_size=3, stride=1, pad=1,
                 ):
        super(ConvBnReLU3D, self).__init__()
        self.conv = nn.Conv3d(in_channels, out_channels,
                              kernel_size, stride=stride, padding=pad, bias=False)
        self.bn = nn.ReLU(inplace=True)
        # self.bn = nn.ReLU()

    def forward(self, x):
        return self.bn(self.conv(x))

class CostRegNet(nn.Module):
    def __init__(self, in_channels):
        super(CostRegNet, self).__init__()
        self.conv0 = ConvBnReLU3D(in_channels, 8)

        self.conv1 = ConvBnReLU3D(8, 16, stride=2)
        self.conv2 = ConvBnReLU3D(16, 16)

        self.conv3 = ConvBnReLU3D(16, 32, stride=2)
        self.conv4 = ConvBnReLU3D(32, 32)

        self.conv5 = ConvBnReLU3D(32, 64, stride=2)
        self.conv6 = ConvBnReLU3D(64, 64)

        self.conv7 = nn.Sequential(
            nn.ConvTranspose3d(64, 32, 3, padding=1, output_padding=1,
                               stride=2, bias=False),
            nn.BatchNorm3d(32))

        self.conv9 = nn.Sequential(
            nn.ConvTranspose3d(32, 16, 3, padding=1, output_padding=1,
                               stride=2, bias=False),
            nn.BatchNorm3d(16))

        self.conv11 = nn.Sequential(
            nn.ConvTranspose3d(16, 8, 3, padding=1, output_padding=1,
                               stride=2, bias=False),
            nn.BatchNorm3d(8))

        # self.conv12 = nn.Conv3d(8, 8, 3, stride=1, padding=1, bias=True)

    def forward(self, x):
        conv0 = self.conv0(x)
        conv2 = self.conv2(self.conv1(conv0))
        conv4 = self.conv4(self.conv3(conv2))

        x = self.conv6(self.conv5(conv4))
        x = conv4 + self.conv7(x)
        del conv4
        x = conv2 + self.conv9(x)
        del conv2
        x = conv0 + self.conv11(x)
        del conv0
        # x = self.conv12(x)
        return x

class PSMNet(nn.Module):
    def __init__(self, maxdisp=192, transform=False):
        super(PSMNet, self).__init__()
        self.maxdisp = maxdisp
        self.transform = transform
        self.feature_extraction = FeatureExtraction(transform)

        self.down = 2
        self.cost_reg = CostRegNet(64)

        self.dres0 = nn.Sequential(
            convbn_3d(64, 32, 3, 1, 1),
            nn.ReLU(inplace=True),
            convbn_3d(32, 32, 3, 1, 1),
            nn.ReLU(inplace=True)
        )
        self.dres1 = nn.Sequential(
            convbn_3d(32, 32, 3, 1, 1),
            nn.ReLU(inplace=True),
            convbn_3d(32, 32, 3, 1, 1)
        )

        self.dres2 = hourglass(32)
        self.dres3 = hourglass(32)
        self.dres4 = hourglass(32)

        self.classif1 = nn.Sequential(
            convbn_3d(32, 32, 3, 1, 1),
            nn.ReLU(inplace=True),
            nn.Conv3d(32, 32, kernel_size=3, padding=1, stride=1, bias=False)
        )
        self.classif2 = nn.Sequential(
            convbn_3d(32, 32, 3, 1, 1),
            nn.ReLU(inplace=True),
            nn.Conv3d(32, 32, kernel_size=3, padding=1, stride=1, bias=False)
        )
        self.classif3 = nn.Sequential(
            convbn_3d(32, 32, 3, 1, 1),
            nn.ReLU(inplace=True),
            nn.Conv3d(32, 32, kernel_size=3, padding=1, stride=1, bias=False)
        )

        # for m in self.modules():
        #     if type(m) == (nn.Conv2d or nn.Conv3d or nn.Linear) :
        #         torch.nn.init.xavier_uniform_(m.weight)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.Conv3d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm3d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.bias.data.zero_()

    def forward(self, img_L, img_R, img_L_transformed=None, img_R_transformed=None):

        if self.transform:
            refimg_feature = self.feature_extraction(img_L, img_L_transformed)  # [bs, 32, H/4, W/4]
            targetimg_feature = self.feature_extraction(img_R, img_R_transformed)
        else:
            refimg_feature = self.feature_extraction(img_L)  # [bs, 32, H/4, W/4]
            targetimg_feature = self.feature_extraction(img_R)

        # Cost Volume
        [bs, feature_size, H, W] = refimg_feature.size()
        cost = torch.FloatTensor(bs, feature_size * 2, self.maxdisp // 4, H, W).zero_().cuda()

        for i in range(self.maxdisp // 4):
            if i > 0:
                cost[:, :feature_size, i, :, i:] = refimg_feature[:, :, :, i:]
                cost[:, feature_size:, i, :, i:] = targetimg_feature[:, :, :, :-i]
            else:
                cost[:, :feature_size, i, :, :] = refimg_feature
                cost[:, feature_size:, i, :, :] = targetimg_feature
        cost = cost.contiguous()  # [bs, fs*2, max_disp/4, H/4, W/4]
        #print(cost.shape)

        #print(cost.shape)
        """
        cost0 = self.dres0(cost)
        cost0 = self.dres1(cost0) + cost0

        out1, pre1, post1 = self.dres2(cost0, None, None)
        #print(out1.shape, cost0.shape)
        out1 = out1 + cost0

        out2, pre2, post2 = self.dres3(out1, pre1, post1)
        out2 = out2 + cost0

        out3, pre3, post3 = self.dres4(out2, pre1, post2)
        out3 = out3 + cost0

        cost1 = self.classif1(out1)
        cost2 = self.classif2(out2) + cost1
        cost3 = self.classif3(out3) + cost2
        """
        cost = F.interpolate(cost, (self.maxdisp//4, 4 * H, 4 * W), mode='trilinear', align_corners=False)

        cost = self.cost_reg(cost)

        if self.training:
            return cost
        else:
            return cost

class Renderer(nn.Module):
    def __init__(self, D=8, W=256, input_ch=3, output_ch=1, input_ch_feat=8, skips=[4], n_rays=1024):
        """
        """
        super(Renderer, self).__init__()
        self.D = D
        self.W = W
        self.n_rays = n_rays
        self.input_ch = input_ch
        #self.input_ch_views = input_ch_views
        self.skips = skips
        #self.use_viewdirs = use_viewdirs
        self.in_ch_pts, self.in_ch_feat = input_ch, input_ch_feat

        self.pts_linears = nn.ModuleList(
            [nn.Linear(self.in_ch_pts, W, bias=True)] + [nn.Linear(W, W, bias=True) if i not in self.skips else nn.Linear(W + self.in_ch_pts, W) for i in range(D-1)])
        self.pts_bias = nn.Linear(input_ch_feat, W)
        #self.views_linears = nn.ModuleList([nn.Linear(input_ch_views + W, W//2)])

        #self.feature_linear = nn.Linear(W, W)
        self.alpha_linear = nn.Linear(W, 1)

        #self.output_linear = nn.Linear(W, output_ch)

        self.pts_linears.apply(weights_init)
        #self.views_linears.apply(weights_init)
        #self.feature_linear.apply(weights_init)
        self.alpha_linear.apply(weights_init)

        self.ray_reg = RayRegression()

        #self.rgb_linear.apply(weights_init)

    def forward(self, x, disp_candidate,B,D):

        dim = x.shape[-1]
        #in_ch_feat = dim-self.in_ch_pts
        input_pts, input_feats = torch.split(x, [self.in_ch_pts, self.in_ch_feat], dim=-1)

        h = input_pts
        bias = self.pts_bias(input_feats)
        for i, l in enumerate(self.pts_linears):
            h = self.pts_linears[i](h) * bias
            h = F.relu(h)
            if i in self.skips:
                h = torch.cat([input_pts, h], -1)

        alpha = torch.relu(self.alpha_linear(h))
        output = alpha.view(B,D,self.n_rays,1)
        pred_disp = self.ray_reg(output, disp_candidate)
        return pred_disp

def weights_init(m):
    if isinstance(m, nn.Linear):
        nn.init.kaiming_normal_(m.weight.data)
        if m.bias is not None:
            nn.init.zeros_(m.bias.data)

if __name__ == '__main__':
    # Test PSMNet
    model = PSMNet(maxdisp=192).cuda()
    model.eval()
    img_L = torch.rand(1, 3, 256, 512).cuda()
    img_R = torch.rand(1, 3, 256, 512).cuda()
    pred = model(img_L, img_R)
    print(f'pred shape {pred.shape}')   # pred shape torch.Size([1, 1, 256, 512])


import subprocess
from math import ceil
from os.path import basename, splitext
from time import sleep

from benchmark.commands import CommandMaker
from benchmark.config import BenchParameters, ConfigError, LocalCommittee, Key
from benchmark.logs import LogParser, ParseError
from benchmark.utils import Print, BenchError, PathMaker

class LocalBench:
    BASE_PORT = 3000

    def __init__(self, bench_parameters_dict):
        try:
            self.bench_parameters = BenchParameters(bench_parameters_dict)
        except ConfigError as e:
            raise BenchError('Invalid nodes or bench parameters', e)

    def __getattr__(self, attr):
        return getattr(self.bench_parameters, attr)

    def _background_run(self, command, log_file):
        name = splitext(basename(log_file))[0]
        cmd = f'{command} 2> {log_file}'
        subprocess.run(['tmux', 'new', '-d', '-s', name, cmd], check=True)

    def _kill_nodes(self):
        try:
            cmd = CommandMaker.kill()
            subprocess.run(cmd, shell=True, stderr=subprocess.DEVNULL)
        except subprocess.SubprocessError as e:
            raise BenchError('Failed to kill testbed', e)

    def run(self, debug=False):
        assert isinstance(debug, bool)
        Print.heading('Starting local benchmark')

        # Kill any previous testbed.
        self._kill_nodes()

        try:
            Print.info('Setting up testbed...')
            nodes, rate = self.nodes[0], self.rate[0]

            # Cleanup all files.
            cmd = f'{CommandMaker.clean_logs()} ; {CommandMaker.cleanup()}'
            subprocess.run([cmd], shell=True, stderr=subprocess.DEVNULL)
            sleep(0.5)  # Removing the store may take time.

            # Recompile the latest code.
            cmd = CommandMaker.compile(self.witness_only).split()
            subprocess.run(cmd, check=True, cwd=PathMaker.node_crate_path())

            # Create alias for the client and nodes binary.
            cmd = CommandMaker.alias_binaries(
                PathMaker.binary_path(), self.witness_only
            )
            subprocess.run([cmd], shell=True)

            # Generate key files for the witnesses.
            key_files = [PathMaker.key_file(i) for i in range(nodes)]
            for key_file in key_files:
                cmd = CommandMaker.generate_key(key_file)
                subprocess.run(cmd.split(), check=True)

            # Generate key file for the IdP.
            idp_key_file = PathMaker.idp_key_file()
            cmd = CommandMaker.generate_key(idp_key_file)
            subprocess.run(cmd.split(), check=True)

            # Generate the committee file.
            idp = Key.from_file(idp_key_file).name
            names = [Key.from_file(x).name for x in key_files]
            committee = LocalCommittee(idp, names, self.BASE_PORT)
            committee.print(PathMaker.committee_file())

            # Run the client (it will wait for the witnesses to be ready).
            cmd = CommandMaker.run_client(
                self.witness_only,
                PathMaker.committee_file(),
                rate,
                self.faults,
                idp_key_file,
                self.batch_size,
                debug
            )
            log_file = PathMaker.client_log_file(0, 0)
            self._background_run(cmd, log_file)

            # Run the IdP.
            if not self.witness_only:
                cmd = CommandMaker.run_idp(
                    idp_key_file,
                    PathMaker.committee_file(),
                    PathMaker.idp_secure_db_path(),
                    PathMaker.sync_db_path(),
                    PathMaker.vkd_db_path(),
                    self.batch_size,
                    debug=debug
                )
                log_file = PathMaker.idp_log_file()
                self._background_run(cmd, log_file)

            # Run the shards (except the faulty ones).
            for i in range(len(committee.addresses(self.faults))):
                cmd = CommandMaker.run_witness(
                    PathMaker.key_file(i),
                    PathMaker.committee_file(),
                    PathMaker.secure_db_path(i, 0),
                    PathMaker.audit_db_path(i, 0),
                    debug=debug
                )
                log_file = PathMaker.shard_log_file(i, 0)
                self._background_run(cmd, log_file)

            # Wait for all transactions to be processed.
            Print.info(f'Running benchmark ({self.duration} sec)...')
            sleep(self.duration)
            self._kill_nodes()

            # Parse logs and return the parser.
            Print.info('Parsing logs...')
            return LogParser.process(PathMaker.logs_path(), faults=self.faults)

        except (subprocess.SubprocessError, ParseError) as e:
            self._kill_nodes()
            raise BenchError('Failed to run benchmark', e)


from socket import *
# Port and server info
serverName = 'localhost'
serverPort = 12000

#Connectig
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))

# User input
#sentence = input("Input lowercase sentence:").encode()
#sentence = "set ploy 1".encode()
sentence = "get ploy".encode()

#sending it to sever
clientSocket.send(sentence)

#This is where you receive info from server after connecting and sendint to server
modifiedSentence = clientSocket.recv(1024)#
print("From Server:", modifiedSentence)
clientSocket.close()


from django.core.management.base import BaseCommand
from django.conf import settings
import json
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update,Bot
from django.views.decorators.csrf import csrf_exempt
from telegram.utils.request import Request
from django.http import HttpResponse
from telegram.ext import (Updater, CommandHandler, CallbackQueryHandler, ConversationHandler, MessageHandler, Filters)
from .main import *
from .messages import *
from .keyboard import *

@csrf_exempt
def webhook(request):
    bot = Bot(
        token=settings.TOKEN,
    )
    updater = Updater(
        bot=bot,
        use_context=True,
    )

    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CallbackQueryHandler(callback_query))
    updater.dispatcher.add_handler(MessageHandler(Filters.text, buttons_work))
    data = json.loads(request.body.decode("utf-8"))
    update = Update.de_json(data, bot)
    updater.dispatcher.process_update(update)

    return HttpResponse("ok")

def set_webhook(request):
    bot = Bot(
        token=settings.TOKEN,
    )
    print(bot.get_me())
    print(bot.get_webhook_info())

    updater = Updater(
        bot=bot,
        use_context=True,
    )

    updater.bot.set_webhook(settings.BASE_URL + "/webhook/" + settings.TOKEN)
    return HttpResponse(settings.BASE_URL + "/webhook/" + settings.TOKEN)

def delete_webhook(request):
    bot = Bot(
        token=settings.TOKEN,
    )
    print(bot.get_me())

    updater = Updater(
        bot=bot,
        use_context=True,
    )

    updater.bot.delete_webhook()
    return HttpResponse("ok")

class Command(BaseCommand):
    help = 'Telegram bot'

    def handle(self, *args, **options):
        request = Request(
            connect_timeout=0.5,
            read_timeout=1.0,
        )

        bot = Bot(
            #request=request,
            token=settings.TOKEN,
            # base_url=settings.PROXY_URL,
        )
        print(bot.get_me())
        updater = Updater(
            bot=bot,
            use_context=True,
        )

        updater.dispatcher.add_handler(CommandHandler('start', start))
        updater.dispatcher.add_handler(CallbackQueryHandler(callback_query))
        updater.dispatcher.add_handler(MessageHandler(Filters.text, buttons_work))
        updater.start_polling()
        updater.idle()

#
# BTN_TODAY, BTN_TOMORROW, BTN_MONTH, BTN_REGION, BTN_DUO = ('⏱ Bugun', '☎Ertaga', '📋 T\'liq taqvim', '🇺🇿 Mintaqa', '🤲 Duo')
# main_buttons = ReplyKeyboardMarkup([
#     [BTN_TODAY], [BTN_TOMORROW, BTN_MONTH], [BTN_REGION], [BTN_DUO]
#     ], resize_keyboard=True)
#
# STATE_REGION = 1
# STATE_CALENDAR = 2
#
#
# def start(update, context):
#     user = update.message.from_user
#
#     buttons = [
#         [
#             InlineKeyboardButton('Jizzax', callback_data='region_1'),
#             InlineKeyboardButton('Toshkent', callback_data='region_2')
#         ]
#     ]
#
#     update.message.reply_html('Assalomu alaykum {}!\nSiz bilan Sulton Abirqulov\n \n'
#     'Ramazon oyi muborak bo\'lsin\n \nKerakli bo\'limni tanlang!'.
#         format(user.first_name), reply_markup=InlineKeyboardMarkup(buttons))
#
#     return STATE_REGION
#
#
# def inline_callback(update, context):
#     try:
#         query = update.callback_query
#         query.message.delete()
#         query.message.reply_html(text='Ramazon taqvimi 2⃣0⃣2⃣1⃣\n \n Quyidagilrdan birini tanlang 👇👇', reply_markup=main_buttons)
#         return STATE_CALENDAR
#
#     except Exception as e:
#         print('error', str(e))
#
#
# def calendar_today(update, context):
#     update.message.reply_text('Bugunni ko\'rish belgilandi.')
#
#
# def calendar_tomorrow(update, context):
#     update.message.reply_text('Ertanni ko\'rish belgilandi.')
#
#
# def calendar_month(update, context):
#     update.message.reply_text('To\'liq taqvim belgilandi.')
#
#
# def select_region(update, context):
#     update.message.reply_text('Region belgilandi.')
#
#
# def select_duo(update, context):
#     update.message.reply_text('Duoni ko\'rish belgilandi.')
#
#
# def main():
#     # updater o'rnatib olamiz
#     updater = Updater('1754370562:AAHMXBJc7nbVoXjFpAI6YG054Ti-pvZrE10', use_context=True)
#
#     # Dispatcher eventlarini aniwlash uchun.
#     dispatcher = updater.dispatcher
#
#     # start kamandasini ushlab qolish uchun
#     # dispatcher.add_handler(CommandHandler('start', start))
#
#     # inline button query
#     # dispatcher.add_handler(CallbackQueryHandler(inline_callback))
#
#     conv_handler = ConversationHandler(
#         entry_points=[CommandHandler('start', start)],
#         states={
#             STATE_REGION: [CallbackQueryHandler(inline_callback)],
#             STATE_CALENDAR: [
#                 MessageHandler(Filters.regex('^('+BTN_TODAY+')$'), calendar_today),
#                 MessageHandler(Filters.regex('^('+BTN_TOMORROW+')$'), calendar_tomorrow),
#                 MessageHandler(Filters.regex('^('+BTN_MONTH+')$'), calendar_month),
#                 MessageHandler(Filters.regex('^('+BTN_REGION+')$'), select_region),
#                 MessageHandler(Filters.regex('^('+BTN_DUO+')$'), select_duo)
#             ],
#         },
#         fallbacks=[CommandHandler('start', start)]
#     )
#     dispatcher.add_handler(conv_handler)
#
#     updater.start_polling()
#     updater.idle()
#
# main()


import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
print('_________________________________')
print(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
print('_________________________________')
print('_________________________________')
print(sys.path)
print('_________________________________')
import cgi
import re
import json
import project.utils as utils
import project.style as style
from docutils.core import publish_parts

from pyramid.httpexceptions import (
    HTTPFound,
    HTTPNotFound,
)

from pyramid.view import view_config

from .models import (
    DBSession,
    SolarSystem,
    Corp,
    CorpType
    )
import json

@view_config(route_name='home')
def root(request):
    return HTTPFound(location = request.route_url('view_system',
                                                  pagename='TestSolarSystem'))

@view_config(route_name='view_system', renderer='templates/main.pt')
def view_system(request):
    pagename = request.matchdict['pagename']
    page = DBSession.query(SolarSystem).filter_by(name=pagename).first()
    pagename_match = re.match('^[a-zA-Z0-9_%]+$', pagename)
    if pagename_match is None:
        return HTTPNotFound('No such Solar System in da Galaxy')
    if page is None:
        return HTTPNotFound('No such Solar System in da Galaxy')

    content = publish_parts(page.name, writer_name='html')['html_body']
    request.context = json.dumps(build_renderer_context(pagename))
    return dict(page=page, content=content)

@view_config(route_name='view_system_selected', renderer='templates/main.pt')
def view_system_selected(request):
    pagename = request.matchdict['pagename']
    corpname = request.matchdict['corpname']
    pagename_match = re.match('^[a-zA-Z0-9_%]+$', pagename)
    corpname_match = re.match('^[a-zA-Z0-9_%]+$', corpname)
    if pagename_match is None:
        return HTTPNotFound('No such Solar System in da Galaxy')
    if corpname_match is None:
        return HTTPNotFound('No such Solar System in da Galaxy')

    page = DBSession.query(SolarSystem).filter_by(name=pagename).first()
    if page is None:
        return HTTPNotFound('No such Solar System in da Galaxy')

    content = publish_parts(page.name, writer_name='html')['html_body']
    request.context = json.dumps(build_renderer_context(pagename, corpname))
    return dict(page=page, content=content)

@view_config(
    route_name='corps',
    renderer='json'
    )
def api_solar_system(request):
    response = {}
    try:
        get = request.GET
    except:
        response['error'] = 'Missing data.'
        return reponse

    if 'solarsystem' in get:
        solarsystem_match = re.match('^[a-zA-Z0-9_%]+$', get['solarsystem'])
        if solarsystem_match is None:
            response['error'] = 'Invalid characters. Only alphanumerical values + "_" are allowed.'
            return response
        else:
            solar_system_name = solarsystem_match.group(0)
    else:
        response['error'] = 'Must define a solar system name.'
        return response

    context = json.dumps(
        build_renderer_context(solar_system_name))

def build_renderer_context(solar_system_name, selected_corp_name=None):
    context = {
        'solar_system': get_solar_system_information(
            solar_system_name, selected_corp_name)
    }
    print('selected_corp_name', selected_corp_name)
    return context

def get_solar_system_information(solar_system_name, selected_corp_name):
    solar_system = DBSession.query(SolarSystem).filter_by(
        name=solar_system_name).first()
    if solar_system is None:
        context['error'] = 'Solar System do not exist. Even if the universe has no limit theoretically.'
        return context
    solar_system = utils.row2dict(solar_system)
    print('solar_system RAG', solar_system)
    corps_tests = corps = DBSession.query(Corp).all()
    corps_tests_2 = DBSession.query(CorpType).all()
    print('corps_tests_2', corps_tests_2)
    print('corps_test', corps_tests)
    corps = DBSession.query(Corp, CorpType).join(
        CorpType,
        CorpType.id == Corp.corp_type_id
    ).all()
    print('corps RAG', corps)
    corps_array = []
    for corp in corps:
        corps_array.append(get_corp_context_from_db(
            corp[0], corp[1]))

    if selected_corp_name is not None:
        solar_system['selected_corp_name'] = selected_corp_name

    solar_system['corps'] = corps_array
    print('sharing...')
    print('solar_system', solar_system)
    return solar_system

def get_corp_context_from_db(corp, corp_type):
    context = {}
    context['texture_path'] = corp.texture_path
    context['id'] = corp.id
    context['name'] = corp.name
    context['mass'] = corp.mass
    context['initial_speed'] = json.loads(corp.initial_speed)
    context['rotation_period'] = corp.rotation_period
    context['initial_position'] = json.loads(corp.initial_position)
    context['distance_friendly_crop'] = corp_type.distance_friendly_crop
    context['corp_type_id'] = corp.corp_type_id

    radius_pixel = style.radius_meter_to_pixel(
        corp.radius)
    context['radius'] = radius_pixel

    context['rotation'] = json.loads(corp.rotation)

    if corp.orbit_coordinate is not None:
        try:
            context['orbit_coordinates'] = json.loads(corp.orbit_coordinate)
        except: pass

    ring_context = {}

    if corp.ring_path is not None:
        ring_context['ring_path'] = corp.ring_path

    if corp.ring_size is not None:
        try:
            ring_context['ring_size'] = style.ring_dimension(
                radius_pixel, int(corp.ring_size))
        except: pass

    if corp.ring_rotation is not None:
        try:
            ring_context['ring_rotation'] = json.loads(
                corp.ring_rotation)
        except: pass

    if len(ring_context) == 3:
        context['ring_context'] = ring_context

    if corp.media_en is not None:
        try:
            #pass
            media = json.loads(
                corp.media_en)
            media = utils.byteify(media)
            #  context['media'] = media
        except: pass

    if corp.parent_corp_id is not None:
        try:
            context['parent_corp_id'] = corp.parent_corp_id
            print(context)
        except: pass

    atmosphere_size = style.atmosphere_thickness(
        radius_pixel, int(corp.atmosphere_size))
    context['atmosphere_context'] = {
        'color': json.loads(corp.atmosphere_color),
        'texture_path': corp.atmosphere_path,
        'size': atmosphere_size
    }
    return context


def computePay(hours,rate):
	print("In compute", hours, rate)
	if(hours > 40):
		reg = hours * rate
		over = (hours - 40) * (rate / 2)
		pay = reg + over

	else:
		pay = fr * ft
	print("Верни", pay)
	return pay

sr = input("Часы")
st = input("Рейтинг")

try:
	fr = float(sr)
	ft = float(st)
except:
	print("Только цифры")
	quit()

xp = computePay(fr,ft)

print("Плата:", xp)


import pandas as pd
from datetime import datetime as dt
import os

df = pd.DataFrame({"my_date": [dt(2022, 1, 1, 0, 0, 0), dt.now()]})

df.info()

write_to_model(df)

model_name = context.current_model.name
df = ref(model_name)
output = f"my_date: {df['my_date'][0]}"
temp_dir = os.environ["temp_dir"]
with open(os.path.join(temp_dir, model_name + ".txt"), "w") as file:
    file.write(output)


n = int(input())
lst = list(map(int,input().split()))
ans = 0

def pncheck(num) :    # 소수인지 확인하는 함수
  div = 0    # num의 약수의 개수
  for i in range(1, num+1) :
    if num % i == 0 :    # num을 1부터 num까지 하나씩 나눠보고, 약수 개수 확인
      div += 1
  if div == 2 :
    return(1)    # 약수의 개수 == 2 면 소수이므로 return(1)
  else :
    return(0)

for i in lst :
  ans += pncheck(i)    # lst의 숫자가 소수이면 ans에 1 추가, 아니면 0 추가. 결국 소수의 개수가 ans에 담긴다.

print(ans)


from py2neo import Graph, Node

import pandas as pd

class CarGraph:
    def __init__(self):
        self.datapath = 'all_cars.csv'
        self.g = Graph("http://localhost:7474", auth=("neo4j", "hulongxing"))    #连接

    def read_nodes(self):
        data = pd.read_csv(self.datapath)   #读取数据

        brand_names = []
        serise_names = []
        scores = []
        levels = []
        structs = []
        EngineORbatterys = []
        SpeedchunkORcharges = []
        types = []
        prices = []
        status = []
        urls =  []

        cars_info = []

        #构建关系
        rel_brand2serise = []   #品牌与车系关系(1:n)
        rel_brand2price = []    #品牌与价格关系(1:n)
        rel_brand2type = []     #品牌与类型关系(1:n)
        rel_brand2urls = []     #品牌与链接关系(1:n)

        rel_name2scores = []    #车系评分关系(1:1)
        rel_serise2levels = []  #车系与车型(轿车、SUV等)关系(1:1)
        rel_serise2struct = []  #车系与车架关系(1:1)
        rel_serise2Engine = []  #车系与引擎关系(OR续航时间)(1:1)
        rel_serise2Chunk = []   #车系与变速器(OR充电时间)关系(1:1)
        rel_serise2type = []    #车系与类型关系(是否为新能源汽车)(1:1)
        rel_serise2price = []   #车系与价格(1:1)
        rel_serise2status = []  #车系与销售状态关系(1:1)
        rel_serise2url = []     #车系链接(1:1)

        current_serise_names = []
        current_prices = []
        current_types = []
        current_urls = []

        current_serise_name = []
        current_price = []
        current_type = []
        current_url = []

        current_brand = data.iloc[0, :]['brand_name']
        for i in range(data.shape[0]):
            car_dict = {}

            car_dict['brand_name'] = data.iloc[i, :]['brand_name']
            car_dict['serise_name'] = data.iloc[i, :]['serise_name']
            car_dict['score'] = data.iloc[i, :]['score']
            car_dict['level'] = data.iloc[i, :]['level']
            car_dict['struct'] = data.iloc[i, :]['struct']
            car_dict['EngineORbattery'] = data.iloc[i, :]['EngineORbattery']
            car_dict['SpeedchunkORcharge'] = data.iloc[i, :]['SpeedchunkORcharge']
            car_dict['type'] = data.iloc[i, :]['type']
            car_dict['price'] = data.iloc[i, :]['price']
            car_dict['status'] = data.iloc[i, :]['status']
            car_dict['url'] = data.iloc[i, :]['url']

            brand_names.append(car_dict['brand_name'])
            serise_names.append(car_dict['serise_name'])
            scores.append(car_dict['score'])
            levels.append(car_dict['level'])
            structs.append(car_dict['struct'])
            EngineORbatterys.append(car_dict['EngineORbattery'])
            SpeedchunkORcharges.append(car_dict['SpeedchunkORcharge'])
            types.append(car_dict['type'])
            prices.append(car_dict['price'])
            status.append(car_dict['status'])
            urls.append(car_dict['url'])

            if current_brand == car_dict['brand_name']:
                #如果之前已经记录了品牌，则
                current_serise_name.append(car_dict['serise_name'])
                current_price.append(car_dict['price'])
                current_type.append(car_dict['type'])
                current_url.append(car_dict['url'])

            else:
                current_serise_names.append(current_serise_name)
                current_prices.append(current_price)
                current_types.append(current_type)
                current_urls.append(current_url)
                current_serise_name, current_price, current_type, current_url = [], [], [], []  #清空操作，为下次做准备
                #如果之前已经记录了品牌，则
                current_serise_name.append(car_dict['serise_name'])
                current_price.append(car_dict['price'])
                current_type.append(car_dict['type'])
                current_url.append(car_dict['url'])
                current_brand = car_dict['brand_name']

            if i == data.shape[0]-1:
                current_serise_names.append(current_serise_name)
                current_prices.append(current_price)
                current_types.append(current_type)
                current_urls.append(current_url)

            rel_name2scores.append([car_dict['serise_name'], car_dict['score']])#车系评分关系(1:1)
            rel_serise2levels.append([car_dict['serise_name'], car_dict['level']])#车系与车型(轿车、SUV等)关系(1:1)
            rel_serise2struct.append([car_dict['serise_name'], car_dict['struct']]) #车系与车架关系(1:1)
            rel_serise2Engine.append([car_dict['serise_name'], car_dict['EngineORbattery']])  #车系与引擎关系(OR续航时间)(1:1)
            rel_serise2Chunk.append([car_dict['serise_name'], car_dict['SpeedchunkORcharge']])  #车系与变速器(OR充电时间)关系(1:1)
            rel_serise2type.append([car_dict['serise_name'], car_dict['type']])  #车系与类型关系(是否为新能源汽车)(1:1)
            rel_serise2price.append([car_dict['serise_name'], car_dict['price']])  #车系与价格(1:1)
            rel_serise2status.append([car_dict['serise_name'], car_dict['status']]) #车系与销售状态关系(1:1)
            rel_serise2url.append([car_dict['serise_name'], car_dict['url']])     #车系链接(1:1)

            cars_info.append(car_dict)
        #添加关系
        convert = list(set(brand_names))
        convert.sort(key=brand_names.index)

        rel_brand2serise = list(zip(convert, current_serise_names))

        rel_brand2price  = list(zip(convert, current_prices))
        rel_brand2type   = list(zip(convert, current_types))
        rel_brand2urls   = list(zip(convert, current_urls))

        return set(brand_names),serise_names,set(scores),set(levels),set(structs) ,set(EngineORbatterys),set(SpeedchunkORcharges),set(types),\
        set(prices),set(status),urls,rel_brand2serise, rel_brand2price, rel_brand2type, rel_brand2urls, rel_name2scores,\
        rel_serise2levels, rel_serise2struct, rel_serise2Engine, rel_serise2Chunk,\
        rel_serise2type, rel_serise2price, rel_serise2status, rel_serise2url, cars_info

        #额外处理一对多的列表

    def create_node(self, label, nodes):
        count = 0
        for node_name in nodes:
            node = Node(label, name=node_name)  #py2neo方法，node_name就是一类节点中的某一个，要建立对象
            self.g.create(node)
            count += 1
            print(count, len(nodes))
        return

    def create_car_nodes(self, cars_info):
        count = 0
        for car_dict in cars_info:
            node = Node("Car", name=car_dict['serise_name'], brand_name=car_dict['brand_name'],
                        score=car_dict['score'] ,level=car_dict['level'],
                        struct=car_dict['struct'],EngineORbattery=car_dict['EngineORbattery'],
                        SpeedchunkORcharge=car_dict['SpeedchunkORcharge'],
                        type=car_dict['type'] , price=car_dict['price'],
                        status=car_dict['status'], url=car_dict['url']
                        )
            self.g.create(node)
            count += 1
            print(count)        #打印每一个品牌的
        return

    '''创建知识图谱实体节点类型schema'''
    def create_graphnodes(self):
        brand_names,serise_names,scores,levels,structs ,EngineORbatterys,SpeedchunkORcharges,types,\
        prices,status,urls,rel_brand2serise, rel_brand2price, rel_brand2type, rel_brand2urls, rel_name2scores,\
        rel_serise2levels, rel_serise2struct, rel_serise2Engine, rel_serise2Chunk,\
        rel_serise2type, rel_serise2price, rel_serise2status, rel_serise2url, cars_info = self.read_nodes()

        self.create_car_nodes(cars_info)
        self.create_node('brand_names', brand_names)
        print(len(brand_names))
        self.create_node('serise_names', serise_names)
        print(len(serise_names))
        self.create_node('scores', scores)
        print(len(scores))
        self.create_node('levels', levels)
        print(len(levels))
        self.create_node('structs', structs)
        print(len(structs))
        self.create_node('EngineORbatterys', EngineORbatterys)
        print(len(EngineORbatterys))
        self.create_node('SpeedchunkORcharges', SpeedchunkORcharges)
        print(len(SpeedchunkORcharges))
        self.create_node('types', types)
        print(len(types))
        self.create_node('prices', prices)
        print(len(prices))
        self.create_node('status', status)
        print(len(status))
        self.create_node('urls', urls)
        print(len(urls))
        return

    def create_relationship(self, start_node, end_node, edges, rel_type, rel_name):
        count = 0
        #                                 # 去重处理  传进来的edges是列表，列表的元素还是列表
        # set_edges = []
        # for edge in edges:              #遍历每一个元素，把###加入进去，之后再分割
        #     set_edges.append('###'.join(edge))
        # all = len(set(set_edges))
        #先判断edge类型，如果是列表，则for循环，如果是字符串则
        for edge in edges:
            p  = edge[0]
            qs = edge[1]
            print(str(type(qs)))

            if str(type(qs)) == "<class 'str'>":
                query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
                start_node, end_node, p, qs, rel_type, rel_name) #关键代码关键代码关键代码！！！创建指定两点之间指定的关系
                try:
                    self.g.run(query)   #pyneo方法
                    print("{}---{}---->{}".format(p, rel_type, qs))
                    count += 1
                    print(rel_type, count, all)
                except Exception as e:
                    print(e)
            else:
                for q in qs:
                    query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
                    start_node, end_node, p, q, rel_type, rel_name) #关键代码关键代码关键代码！！！创建指定两点之间指定的关系

                    try:
                        self.g.run(query)   #pyneo方法
                        print("{}---{}---->{}".format(p, rel_type, q))
                        count += 1
                        print(rel_type, count, all)
                    except Exception as e:
                        print(e)

        # for edge in set(set_edges):     #去重主要是使用了set，set中的元素各不相同。
        #     edge = edge.split('###')    #还原
        #     p = edge[0]                 #p是起始点，如百日咳
        #     q = edge[1]                 #q是终点，  如清蒸鸡蛋羹
        #     query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{name:'%s'}]->(q)" % (
        #         start_node, end_node, p, q, rel_type, rel_name) #关键代码关键代码关键代码！！！创建指定两点之间指定的关系

        #     try:
        #         self.g.run(query)   #pyneo方法
        #         count += 1
        #         print(rel_type, count, all)
        #     except Exception as e:
        #         print(e)
        return

    def create_graphrels(self):
        brand_names,serise_names,scores,levels,structs ,EngineORbatterys,SpeedchunkORcharges,types,\
        prices,status,urls,rel_brand2serise, rel_brand2price, rel_brand2type, rel_brand2urls, rel_name2scores,\
        rel_serise2levels, rel_serise2struct, rel_serise2Engine, rel_serise2Chunk,\
        rel_serise2type, rel_serise2price, rel_serise2status, rel_serise2url, cars_info = self.read_nodes()

        self.create_relationship('brand_names', 'Car', rel_brand2serise, 'has_serises', '拥有车系')
        # self.create_relationship('brand_names', 'prices', rel_brand2price, 'brand_price', '汽车价格')
        # self.create_relationship('brand_names', 'types', rel_brand2type, 'brand_types', '类型')
        # self.create_relationship('brand_names', 'urls', rel_brand2urls, 'brand_url', '链接')

        self.create_relationship('Car', 'scores', rel_name2scores, 'serise_score', '评分')
        self.create_relationship('Car', 'levels', rel_serise2levels, 'serise_level', '级别')
        self.create_relationship('Car', 'structs', rel_serise2struct, 'serise_struct', '架构')
        self.create_relationship('Car', 'EngineORbatterys', rel_serise2Engine, 'serise_engine', '引擎OR续航')
        self.create_relationship('Car', 'SpeedchunkORcharges', rel_serise2Chunk, 'serise_chunk', '变速箱OR充电')
        self.create_relationship('Car', 'types', rel_serise2type, 'serise_type', '类型')
        self.create_relationship('Car', 'status', rel_serise2status, 'serise_status', '销售状态')
        self.create_relationship('Car', 'urls', rel_serise2url, 'serise_urls', '链接')

    def export_data(self):
        brand_names,serise_names,scores,levels,structs ,EngineORbatterys,SpeedchunkORcharges,types,\
        prices,status,urls,rel_brand2serise, rel_brand2price, rel_brand2type, rel_brand2urls, rel_name2scores,\
        rel_serise2levels, rel_serise2struct, rel_serise2Engine, rel_serise2Chunk,\
        rel_serise2type, rel_serise2price, rel_serise2status, rel_serise2url, cars_info = self.read_nodes()

        f_brand_names           = open('brand_names.txt', 'w+', encoding='utf-8')
        f_serise_names          = open('serise_names.txt', 'w+', encoding='utf-8')
        f_scores                = open('scores.txt', 'w+', encoding='utf-8')
        f_levels                = open('levels.txt', 'w+', encoding='utf-8')
        f_structs               = open('structs.txt', 'w+', encoding='utf-8')
        f_EngineORbatterys      = open('EngineORbatterys.txt', 'w+', encoding='utf-8')
        f_SpeedchunkORcharges   = open('SpeedchunkORcharges.txt', 'w+', encoding='utf-8')
        f_types                 = open('types.txt', 'w+', encoding='utf-8')
        f_prices                = open('prices.txt', 'w+', encoding='utf-8')
        f_status                = open('status.txt', 'w+', encoding='utf-8')
        f_urls                  = open('urls.txt', 'w+', encoding='utf-8')

        f_brand_names.write('\n'.join(list(brand_names)))
        f_serise_names.write('\n'.join(list(serise_names)))
        f_scores.write('\n'.join(list(scores)))
        f_levels.write('\n'.join(list(levels)))
        print(structs)
        f_structs.write('\n'.join(list(structs)))
        f_EngineORbatterys.write('\n'.join(list(EngineORbatterys)))
        f_SpeedchunkORcharges.write('\n'.join(list(EngineORbatterys)))
        f_types.write('\n'.join(list(types)))
        f_prices.write('\n'.join(list(prices)))
        f_status.write('\n'.join(list(status)))
        f_urls.write('\n'.join(list(urls)))

        f_brand_names.close()
        f_serise_names.close()
        f_scores.close()
        f_levels.close()
        f_structs.close()
        f_EngineORbatterys.close()
        f_types.close()
        f_prices.close()
        f_status.close()
        f_urls.close()
        return

if __name__ == '__main__':
    handler = CarGraph()
    handler.export_data()
    handler.create_graphnodes()
    handler.create_graphrels()


import os
import shutil

train_filenames = os.listdir('../data/train')
train_cat = filter(lambda x:x[:3] == 'cat', train_filenames)
train_dog = filter(lambda x:x[:3] == 'dog', train_filenames)

def rmrf_mkdir(dirname):
    if os.path.exists(dirname):
        shutil.rmtree(dirname)
    os.mkdir(dirname)

rmrf_mkdir('../data/train2')
os.mkdir('../data/train2/cat')
os.mkdir('../data/train2/dog')

rmrf_mkdir('../data/test2')
os.symlink('../data/test/', '../data/test2/test')

for filename in train_cat:
    os.symlink('../data/train/'+filename, '../data/train2/cat/'+filename)

for filename in train_dog:
    os.symlink('../data/train/'+filename, '../data/train2/dog/'+filename)