import os
from pickle import FALSE

sw  = 0

num = 0

lista     = []
lista2 = []
suscripcion = []

ingreso_opciones_menu1 = 0
errorIngresoSTR = "INGRESE SOLO NUMEROS"
errorIngreso123 = "escoja la opcion de 1 al 4"

rutTexto = 0
rut = 0
valida_rut = False
nombre = 0
direccion = 0
comuna = 0
correo = 0
edad_texto = 0
edad = 0
genero = 0
celu_texto = 0
celu = 0
tipo_cuenta = 0
fecha_suscripcion = 0
contador = 0
suscrito = False
existe_usuario = False
contador2 = 0

caracteresPermitidosRut = ["0'","1","2","3","4","5","6","7","8","9",]

menu1 = ['Juan Maestro APP','    (1) Registrar Cliente','    (2) Suscripción', '    (3) Consultar Datos Cliente','    (4) Salir']

while sw == 0:
    for i in menu1:
        print (i)
        sw = 1

    try:
        ingreso_opciones_menu1 = int (input("ingrese la opción: "))
        os.system("clear")

        if ingreso_opciones_menu1 == 1:
            print ("----------------------------------------------")
            print ("          opcion 1 -  Registrar Cliente       ")
            print ("----------------------------------------------")
            while True:
                    try:
                        rutTexto = input("registre su Rut, sin dígito verificador ni puntos: ")

                        for caracter in rutTexto:
                            if caracter not in caracteresPermitidosRut:
                                raise AssertionError('Ha ingresado un caracter invalido')

                        rut = int(rutTexto)
                        if rut >= 4000000 and rut <= 999999999:
                            break
                        else:
                            os.system("clear")
                            print ("----------------------------------------------")
                            print ("           NO ES UN RUT VALIDO")
                            print ("----------------------------------------------")
                            sw2 = 0
                    except AssertionError as ae:
                        os.system("clear")
                        print ("----------------------------------------------")
                        print ("   ", ae, "   ")
                        print ("----------------------------------------------")
                        sw = 0
                    except ValueError:
                        os.system("clear")
                        print ("----------------------------------------------")
                        print ("   INGRESE SIN PUNTOS NI LETRAS NI GUIONES")
                        print ("----------------------------------------------")
                        sw = 0

            sw = 0
            nombre    = (input("registre su nombre    : "))
            direccion = (input("registre su Dirección : "))
            comuna    = (input("registre su Comuna    : "))

            while True:
                mail = (input ("ingrese mail          : "))
                if "@" in mail:
                    break
                else:
                    print ("----------------------------------------------")
                    print ("  NO ES UN MAIL VALIDO, NO OLVIDE INGRESAR @  ")
                    print ("----------------------------------------------")

            sw = 0
            while True:
                    try:
                        edad_texto = (input("registre su Edad    : "))
                        for caracter in rutTexto:
                            if caracter not in caracteresPermitidosRut:
                                raise AssertionError('Ha ingresado un caracter invalido')

                        edad = int(edad_texto)
                        if edad >= 1 and edad <= 110:
                            break
                        else:
                            print ("----------------------------------------------")
                            print ("    NO ES EDAD CORRECTA, IGRESE NUEVAMENTE    ")
                            print ("----------------------------------------------")
                    except AssertionError as ae:
                            os.system("clear")
                            print ("----------------------------------------------")
                            print ("   ", ae, "   ")
                            print ("----------------------------------------------")
                            sw = 0
                    except ValueError:
                        print ("----------------------------------------------")
                        print ("           INGRESE SOLO NUMEROS               ")
                        print ("----------------------------------------------")

            sw = 0
            while True:
                genero = (input("ingrese su genero con f/m: "))
                if genero == "f" or genero == "m":
                    break
                else:
                    print ("----------------------------------------------")
                    print ("      OPCION NO VALIDA, IGRESE NUEVAMENTE     ")
                    print ("----------------------------------------------")

            sw = 0
            while True:
                try:
                    celu_texto = (input("registre su número de teléfono    : "))
                    for caracter in celu_texto:
                        if caracter not in caracteresPermitidosRut:
                            raise AssertionError('Ha ingresado un caracter invalido')

                    celu = int(celu_texto)
                    if celu >= 90000000 and celu <= 99999999:
                        break
                    else:
                        print ("----------------------------------------------")
                        print ("      ERROR DE INGRESO, IGRESE NUEVAMENTE     ")
                        print ("----------------------------------------------")
                except AssertionError as ae:
                        os.system("clear")
                        print ("----------------------------------------------")
                        print ("   ", ae, "   ")
                        print ("----------------------------------------------")
                        sw = 0
                except ValueError:
                    print ("----------------------------------------------")
                    print ("           INGRESE SOLO NUMEROS               ")
                    print ("----------------------------------------------")

            sw = 0
            while True:
                tipo_cuenta = (input("ingrese Tipo de cuenta (a)Premium (b)Gold (c)Silver "))
                if tipo_cuenta ==  "a":
                    tipo_cuenta = "Premium"
                    break
                if tipo_cuenta == "b":
                    tipo_cuenta = "Gold"
                    break
                if tipo_cuenta == "c":
                    tipo_cuenta = "Silver"
                    break
                else:
                    print ("----------------------------------------------")
                    print ("      OPCION NO VALIDA, IGRESE NUEVAMENTE     ")
                    print ("----------------------------------------------")
            # concat = rut, nombre, direccion, comuna, mail, edad, genero,celu,tipo_cuenta
            # nuevo_usuario = []
            # nuevo_usuario.append (rutTexto)
            # nuevo_usuario.append (nombre)
            # nuevo_usuario.append (direccion)
            # nuevo_usuario.append (comuna)
            # nuevo_usuario.append (correo)
            # nuevo_usuario.append (edad_texto)
            # nuevo_usuario.append (genero)
            # nuevo_usuario.append (celu_texto)
            # nuevo_usuario.append (tipo_cuenta)
            # lista.append(nuevo_usuario)
            lista2 = []
            lista2.append (rutTexto)
            lista2.append (nombre)
            lista2.append (direccion)
            lista2.append (comuna)
            lista2.append (correo)
            lista2.append (edad_texto)
            lista2.append (genero)
            lista2.append (celu_texto)
            lista2.append (tipo_cuenta)
            lista.append(lista2)
            contador = contador + 1
            print("")
            print ("----------------------------------------------")
            print ("       El registro finalizó con éxito")
            print ("----------------------------------------------")
            print ("")
            print ("presione ENTER para continuar")
            input ("")
            os.system("clear")

            sw = 0
#----------------------------------------------------------------- OPCION 2 ---------------------------------------------------------
        if ingreso_opciones_menu1 == 2:
            print ("----------------------------------------------")
            print ("          opcion 2 -  Suscripción             ")
            print ("----------------------------------------------")
            sw = 1
            while True:
                    try:
                        rutTexto = input("registre su Rut, sin dígito verificador ni puntos: ")
                        if contador == 0:
                            print ("")
                            print ("El usuario no existe, favor registrar usuario en opción (1)")
                            print ("")
                            print ("presione ENTER para continuar")
                            input ("")
                            os.system("clear")

                        for caracter in rutTexto:
                            if caracter not in caracteresPermitidosRut:
                                raise AssertionError('Ha ingresado un caracter invalido')
                        for usuario in lista:
                            if usuario[0] == rutTexto:
                                existeUsuario = True
                                print ("si existe")

                                fecha_suscripcion = input("ingrese fecha de solicitud")
                                suscripcion = []
                                suscripcion.append(fecha_suscripcion)
                                print("fecha de solicitud ingresada con éxito")
                                break
                            else:
                                print ("")
                                print ("El usuario no existe, favor registrar usuario en opción (1)")
                                print ("")
                                print ("presione ENTER para continuar")
                                input ("")
                                os.system("clear")

                        rut = int(rutTexto)
                        if rut >= 4000000 and rut <= 999999999:
                            break
                        else:
                            os.system("clear")
                            print ("----------------------------------------------")
                            print ("           NO ES UN RUT VALIDO")
                            print ("----------------------------------------------")
                            sw2 = 0
                    except AssertionError as ae:
                        os.system("clear")
                        print ("----------------------------------------------")
                        print ("   ", ae, "   ")
                        print ("----------------------------------------------")
                        sw = 0
                    except ValueError:
                        os.system("clear")
                        print ("----------------------------------------------")
                        print ("   INGRESE SIN PUNTOS NI LETRAS NI GUIONES")
                        print ("----------------------------------------------")
                        sw = 0

            sw = 0

        #----------------------------------------------------------------- OPCION 3 ---------------------------------------------------------

        if ingreso_opciones_menu1 == 3:
            print ("----------------------------------------------")
            print ("     opcion 3 -  Consultar Datos Cliente      ")
            print ("----------------------------------------------")
            sw = 1
            while True:
                    try:
                        rutTexto = input("registre su Rut, sin dígito verificador ni puntos: ")
                        if contador == 0:
                            print ("")
                            print ("El usuario no existe, favor registrar usuario en opción (1)")
                            print ("")
                            print ("presione ENTER para continuar")
                            input ("")
                            os.system("clear")
                        for caracter in rutTexto:
                            if caracter not in caracteresPermitidosRut:
                                raise AssertionError('Ha ingresado un caracter invalido')

                        rut = int(rutTexto)
                        if rut >= 4000000 and rut <= 999999999:
                            break
                        else:
                            os.system("clear")
                            print ("----------------------------------------------")
                            print ("           NO ES UN RUT VALIDO")
                            print ("----------------------------------------------")
                            sw2 = 0
                    except AssertionError as ae:
                        os.system("clear")
                        print ("----------------------------------------------")
                        print ("   ", ae, "   ")
                        print ("----------------------------------------------")
                        sw = 0
                    except ValueError:
                        os.system("clear")
                        print ("----------------------------------------------")
                        print ("   INGRESE SIN PUNTOS NI LETRAS NI GUIONES")
                        print ("----------------------------------------------")
                        sw = 0

            sw = 0
            existeUsuario = False

            for usuario in lista:
                if usuario[0] == rutTexto:
                    existeUsuario = True
                    print ("Rut       : ", usuario[0],
                         "\nNombre    : ", usuario[1],
                         "\nDirección : ", usuario[2],
                         "\nComuna    : ", usuario[3],
                         "\nCorreo    : ", usuario[4],
                         "\nEdad      : ", usuario[5],
                         "\nGénero    : ", usuario[6],
                         "\nCelular   : ", usuario[7],
                         "\nCuenta    : ", usuario[8])

            sw = 0
#----------------------------------------------------------------- OPCION 4 ---------------------------------------------------------

        if ingreso_opciones_menu1 == 4:
            print ("----------------------------------------------")
            print ("             opcion 4 -  Salir                ")
            print ("----------------------------------------------")
            print ("")
            print ("Gracias por suscribirse a la App de Juan Maestro…")
            print ("")
            print ("------------  FIN DEL PROGRAMA ---------------")
            sw = 1

        if ingreso_opciones_menu1 >= 5:
            print ("----------------------------------------------")
            print (errorIngreso123)
            print ("----------------------------------------------")
            sw = 0

    except ValueError:
        os.system("clear")
        print ("----------------------------------------------")
        print (errorIngresoSTR)
        print ("----------------------------------------------")
        sw = 0


import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import random

random.seed(92)

#   Results dataframe
df = pd.DataFrame([['development data (test set)', 96.38, 98.71, 98.95, 99.02, 99.23],
                   ['PPMI dataset', 97.51, 99.12, 99.23, 99.31, 99.38],
                   ['MPH dataset', 93.46, 92.42, 95.73, 96.12, 96.24]],
                   columns=['dataset', 'SBR', 'PCA-RFC', 'CNN-MVT', 'CNN-RLT', "CNN-Regression"])

palette = sns.color_palette("tab10", 7)
random.shuffle(palette)

target_figsize = (6, 6)

ax = df.plot(x='dataset',
            kind='bar',
            stacked=False,
            xlabel='',
            ylabel='AUC (%) of Balanced Accuracy over PIncObs',
            ylim=(90,100),
            color=palette,
            edgecolor='white',
            width=0.7,
            linewidth=2,
            figsize=target_figsize,
            zorder=5)

"""
for p in ax.patches:
    ax.annotate(str(p.get_height()), (p.get_x() + p.get_width() / 2., p.get_height()),
                ha='center', va='center', xytext=(0, 10), textcoords='offset points', fontsize=10)
"""

ax.grid(axis='y', zorder=0)
ax.set_yticks(range(90, 101, 1))
ax.set_xticklabels(df['dataset'], rotation=0)

plt.tight_layout()
plt.savefig("/Users/aleksej/IdeaProjects/master-thesis-kucerenko/src/results/evaluations/auc_main_comparison.png",
            dpi=300)


# -*- coding: utf-8 -*-
"""Setup file for the Data_cleaning_tools project.
"""

import codecs
import os.path
import re
import sys
from setuptools import setup, find_packages

# avoid a from get_zipcode_from_gmap import __version__ as version (that compiles get_zipcode_from_gmap.__init__ and is not compatible with bdist_deb)
version = None
for line in codecs.open(os.path.join('get_zipcode_from_gmap', '__init__.py'), 'r', encoding='utf-8'):
    matcher = re.match(r"""^__version__\s*=\s*['"](.*)['"]\s*$""", line)
    version = version or matcher and matcher.group(1)

# get README content from README.md file
with codecs.open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding='utf-8') as fd:
    long_description = fd.read()

setup(
    name='get_zipcode_from_gmap',
    version=version,
    description='No description yet.',
    long_description=long_description,
    author='maito',
    author_email='maito.tauchi@en-japan.io',
    license='GPL-3',
    url='',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    test_suite='get_zipcode_from_gmap.tests',
    install_requires=[],
    setup_requires=[],
    classifiers=[],
)


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 07:37:55 2019

@author: Vimotus
"""

import numpy as np
import os
from optparse import OptionParser
import sys
import networkx as nx
import time
from gensim.models import Word2Vec

walks=list()
rfile=open("D:\\代码\\C\\刘子图\\基于事件相关的影响范围预测\\事件影响表达\\data\\数据集1280\\all_walks.txt",'r')
temp='D:\\代码\\C\\刘子图\\基于事件相关的影响范围预测\\事件影响表达\\data\\数据集1280\\影响表达\\vector'
temp1='.txt'
t=0

for line in rfile:
    line=line.rstrip('\n')
    #print(type(line))
    #print(line)
    walk_strings=line.split('\t')
    #print(type(walk_strings))
    #print(walk_strings[0])
    del(walk_strings[0])
    #print(walk_strings)
    #print(type(walk_strings))
    #test=" ".join(walk_strings)
    #walks.append(test.split(" "))
    for i in range(0,walk_strings.__len__()):
        walk_str=walk_strings[i][:-1]
        #print(type(walk_str))
        #print(walk_str.split("  "))
        walks.append(walk_str.split())
    if t==0 :
        model=Word2Vec(walks,size=50,window=10,min_count=0, sg=1,workers=5,iter=8)
        t=t+1
    if t>0:
        model.build_vocab(walks,update=True)
        model.train(walks,total_examples=model.corpus_count,epochs=model.iter)
        path=temp+str(t)+temp1
        t=t+1
        model.wv.save_word2vec_format(path)
    print(t)
#model=Word2Vec.load("D:\\代码\\C\\刘子图\\data\\3200事件数据集\\data\\vector_test.txt")
'''

model.wv.save_word2vec_format("D:\\代码\\C\\刘子图\\基于事件相关的影响范围预测\\事件影响表达\\data\\数据集1280\\vector.txt")
model.save("D:\\代码\\C\\刘子图\\基于事件相关的影响范围预测\\事件影响表达\\data\\数据集1280\\temp.txt")
print("1111")
rfile.close()
temp='D:\\代码\\C\\刘子图\\基于事件相关的影响范围预测\\事件影响表达\\data\\数据集1280\\影响表达\\vector'
temp1='.txt'
t=0
rfile=open("D:\\代码\\C\\刘子图\\基于事件相关的影响范围预测\\事件影响表达\\data\\数据集1280\\time_val.txt",'r')
for line in rfile:
    walks.clear()
    line=line.rstrip('\n')
    walk_strings=line.split('\t')
    del(walk_strings[0])
    for i in range(0,walk_strings.__len__()):
        walk_str=walk_strings[i][:-1]
        walks.append(walk_str.split())
    model.build_vocab(walks,update=True)
    model.train(walks,total_examples=model.corpus_count,epochs=model.iter)
    path=temp+str(t)+temp1
    t=t+1
    model.wv.save_word2vec_format(path)
rfile.close()
rfile=open("D:\\代码\\C\\刘子图\\基于事件相关的影响范围预测\\事件影响表达\\data\\数据集1280\\time_test.txt",'r')
for line in rfile:
    walks.clear()
    line=line.rstrip('\n')
    walk_strings=line.split('\t')
    del(walk_strings[0])
    for i in range(0,walk_strings.__len__()):
        walk_str=walk_strings[i][:-1]
        walks.append(walk_str.split())
    model.build_vocab(walks,update=True)
    model.train(walks,total_examples=model.corpus_count,epochs=model.iter)
    path=temp+str(t)+temp1
    t=t+1
    model.wv.save_word2vec_format(path)'''


import tools

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y

def main():
    while True:
        print("Vyber operaciu")
        print("1. add")
        print("2. subtract")
        print("3. multiply")
        print("4. divide")
        print("5. add from file")

        volba = input("Zadaj voľbu (1, 2, 3, 4, 5)")
        print(volba)

        if volba in ("1", "2", "3", "4", "5"):
            if volba == "5":
                nums = tools.load_nums_from_file()
                for pair in nums:
                    x = pair[0]
                    y = pair[1]
                    print(f"{x} + {y} = {add(x, y)}")
            else:
                x = float(input("enter first number"))
                y = float(input("enter second number"))
                if volba == "1":
                    print(f" {x}, +, {y}, = {add(x, y)}")
                elif volba == "2":
                    print(f" {x}, -, {y},  = {subtract(x, y)}")
                elif volba == "3":
                    print(f" {x}, *, {y}, = {multiply(x, y)}")
                elif volba == "4":
                    print(f" {x}, /, {y}, = {divide(x, y)}")
        else:
            print("Zlá voľba")

if __name__ == "__main__":
    main()


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

class Node(object):
    __slots__ = ('value', 'prev', 'next')   # save memory

    def __init__(self, value=None, prev=None, next=None):
        self.value, self.prev, self.next = value, prev, next

class CircularDoubleLinkedList(object):
    """循环双端链表 ADT
    多了个循环其实就是把 root 的 prev 指向 tail 节点，串起来
    """

    def __init__(self, maxsize=None):
        self.maxsize = maxsize
        node = Node()
        node.next, node.prev = node, node
        self.root = node
        self.length = 0

    def __len__(self):
        return self.length

    def headnode(self):
        return self.root.next

    def tailnode(self):
        return self.root.prev

    def append(self, value):    # O(1), 你发现一般不用 for 循环的就是 O(1)，有限个步骤
        if self.maxsize is not None and len(self) >= self.maxsize:
            raise Exception('LinkedList is Full')
        node = Node(value=value)
        tailnode = self.tailnode() or self.root

        tailnode.next = node
        node.prev = tailnode
        node.next = self.root
        self.root.prev = node
        self.length += 1

    def appendleft(self, value):
        if self.maxsize is not None and len(self) >= self.maxsize:
            raise Exception('LinkedList is Full')
        node = Node(value=value)
        if self.root.next is self.root:   # empty
            node.next = self.root
            node.prev = self.root
            self.root.next = node
            self.root.prev = node
        else:
            node.prev = self.root
            headnode = self.root.next
            node.next = headnode
            headnode.prev = node
            self.root.next = node
        self.length += 1

    def remove(self, node):      # O(1)，传入node 而不是 value 我们就能实现 O(1) 删除
        """remove
        :param node  # 在 lru_cache 里实际上根据key 保存了整个node:
        """
        if node is self.root:
            return
        else:    #
            node.prev.next = node.next
            node.next.prev = node.prev
        self.length -= 1
        return node

    def iter_node(self):
        if self.root.next is self.root:
            return
        curnode = self.root.next
        while curnode.next is not self.root:
            yield curnode
            curnode = curnode.next
        yield curnode

    def __iter__(self):
        for node in self.iter_node():
            yield node.value

    def iter_node_reverse(self):
        """相比单链表独有的反序遍历"""
        if self.root.prev is self.root:
            return
        curnode = self.root.prev
        while curnode.prev is not self.root:
            yield curnode
            curnode = curnode.prev
        yield curnode

def test_double_link_list():
    dll = CircularDoubleLinkedList()
    assert len(dll) == 0

    dll.append(0)
    dll.append(1)
    dll.append(2)

    assert list(dll) == [0, 1, 2]

    assert [node.value for node in dll.iter_node()] == [0, 1, 2]
    assert [node.value for node in dll.iter_node_reverse()] == [2, 1, 0]

    headnode = dll.headnode()
    assert headnode.value == 0
    dll.remove(headnode)
    assert len(dll) == 2
    assert [node.value for node in dll.iter_node()] == [1, 2]

    dll.appendleft(0)
    assert [node.value for node in dll.iter_node()] == [0, 1, 2]

if __name__ == '__main__':
    test_double_link_list()


'''
A sourcecode to initialize the program.
It defines global variables and constraints.
'''

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

# Configuration
import os
import sys
rootpath = os.path.sep.join(os.path.dirname(os.path.abspath(__file__)).split(os.path.sep)[:-1])
sys.path.append(rootpath)

from object import Activity, Grid, Project
from naviutil import NaviPath, NaviFunc, NaviIO
navipath = NaviPath()
navifunc = NaviFunc()
naviio = NaviIO()

import pickle as pk
import pandas as pd
from copy import deepcopy
from collections import defaultdict

def init_activity_book():
    global fname_activity_book

    activity_table = pd.read_excel(navipath.activity_table)

    activity_book = {}
    for _, line in activity_table.iterrows():
        category = line['category']
        major = line['major_activity']
        minor = line['minor_activity']
        code = line['code']
        productivity = line['productivity']
        pre_dist = line['pre_dist']

        parameters = {
            'category': category,
            'major': major,
            'minor': minor,
            'code': code,
            'productivity': productivity,
            'pre_dist': pre_dist,
        }
        activity_book[code] = Activity(parameters=parameters)

    os.makedirs(navipath.fdir_component, exist_ok=True)
    with open(os.path.sep.join((navipath.fdir_component, fname_activity_book)), 'wb') as f:
        pk.dump(activity_book, f)

    print('============================================================')
    print('Init ActivityBook')
    print('  | fdir : {}'.format(navipath.fdir_component))
    print('  | fname: {}'.format(fname_activity_book))

def set_orders_in_activity_book():
    global fname_activity_book

    with open(os.path.sep.join((navipath.fdir_component, fname_activity_book)), 'rb') as f:
        activity_book = pk.load(f)

    activity_order = pd.read_excel(navipath.activity_order)
    key_errors = []
    for _, line in activity_order.iterrows():
        predecessor_code = line['predecessor']
        successor_code = line['successor']

        try:
            predecessor_activity = deepcopy(activity_book[predecessor_code])
        except KeyError:
            key_errors.append(predecessor_code)
            continue
        try:
            successor_activity = deepcopy(activity_book[successor_code])
        except KeyError:
            key_errors.append(successor_code)
            continue

        predecessor_activity.add_successor(successor_activity.code)
        successor_activity.add_predecessor(predecessor_activity.code)

        activity_book[predecessor_code] = predecessor_activity
        activity_book[successor_code] = successor_activity

    updates = [True]
    while any(updates) == True:
        updates = []
        for activity_code in activity_book:
            activity = activity_book[activity_code]

            existing_preds = deepcopy(list(set(activity.predecessor)))
            for pred_code in activity.predecessor:
                pred_of_pred = list(set(activity_book[pred_code].predecessor))
                updated_preds = deepcopy(list(set(existing_preds+pred_of_pred)))
                if set(updated_preds) != set(existing_preds):
                    activity_book[activity_code].predecessor = updated_preds
                    updates.append(True)

            existing_succs = deepcopy(list(set(activity.successor)))
            for succ_code in activity.successor:
                succ_of_succ = list(set(activity_book[succ_code].successor))
                updated_succs = deepcopy(list(set(existing_succs+succ_of_succ)))
                if set(updated_succs) != set(existing_succs):
                    activity_book[activity_code].successor = updated_succs
                    updates.append(True)

    with open(os.path.sep.join((navipath.fdir_component, fname_activity_book)), 'wb') as f:
        pk.dump(activity_book, f)

    print('============================================================')
    print('Set order information to ActivityBook')
    print('  | fdir : {}'.format(navipath.fdir_component))
    print('  | fname: {}'.format(fname_activity_book))

    if key_errors:
        print('Errors on ActivityOrder template')
        key_errors = list(set(key_errors))
        for activity_code in key_errors:
            print('  | Absent in ActivityBook: {}'.format(activity_code))
    else:
        pass

def define_works(case_num):
    global fname_activity_book

    with open(os.path.sep.join((navipath.fdir_component, fname_activity_book)), 'rb') as f:
        activity_book = pk.load(f)

    case_data = pd.read_excel(navipath.case(case_num))
    works = defaultdict(list)
    for idx, line in case_data.iterrows():
        x = int(line['x'])
        y = int(line['y'])
        z = int(line['z'])
        location = '{}_{}_{}'.format(x, y, z)

        try:
            activity_code = line['code']
            activity = activity_book[activity_code]
        except KeyError:
            continue

        works[location].append(activity)

    return works

def initiate_project(case_num, duration):
    works = define_works(case_num)
    grids = []
    for loc in works:
        grids.append(Grid(location=loc, works=works[loc]))

    project = Project(grids=grids, duration=duration)
    project.summary()

    os.makedirs(navipath.fdir_proj, exist_ok=True)
    with open(navipath.proj(case_num), 'wb') as f:
        pk.dump(project, f)

    print('============================================================')
    print('Init Project')
    print('  | fdir : {}'.format(navipath.fdir_proj))
    print('  | fname: {}'.format(os.path.basename(navipath.proj(case_num))))

def export_initial_schedule(case_num):
    with open(navipath.proj(case_num), 'rb') as f:
        project = pk.load(f)

    fname_schedule = 'C-{}.xlsx'.format(case_num)
    schedule = navifunc.grids2schedule(grids=project.sorted_grids)
    naviio.schedule2xlsx(schedule=schedule, fname=fname_schedule)

if __name__ == '__main__':
    ## Project Constraints
    fname_activity_book = 'activity_book.pk'

    try:
        case_num = str(sys.argv[1])
    except:
        print('Insert project case number: ')
        sys.exit()

    try:
        duration = int(sys.argv[2])
    except:
        print('Insert project duration (total days): ')
        sys.exit()

    ## Activity Book
    init_activity_book()
    set_orders_in_activity_book()

    ## Project
    define_works(case_num)
    initiate_project(case_num, duration)

    ## Schedule
    export_initial_schedule(case_num)


# Programming and Scripting
# Problem Set 1
# Week 2
# Author: Megan O'Donovan

weight = int(input('Enter weight(kg):'))
height = int(input('Enter height(cm):'))
# BMI is measured using kg and meters squared - height measured in cm must be changed
newheight = (height/100)**2
# round to 2 decimal places
bmivalue = round(weight/newheight,2)
print('The BMI is (kg/m^2) {}.' .format(bmivalue))


# -*- coding: UTF-8 -*-
import sys
import os
import json
from pathlib import Path

CUR_PATH = os.path.dirname(os.path.realpath(__file__))
INSTALL_FILE = str(Path(os.path.join(CUR_PATH, "../config/deploy_param.json")))

info = {}

with open(INSTALL_FILE, encoding="utf-8") as f:
    _tmp = f.read()
    info = json.loads(_tmp)

def get_value():
    param = sys.argv[1]

    # deploy_user 格式为：用户:用户组
    if param == 'deploy_user':
        return info.get('deploy_user').split(':')[0]

    if param == 'deploy_group':
        return info.get('deploy_user').split(':')[1]

    return info.get(param)

if __name__ == "__main__":
    res = get_value()
    print(res)


from authentications.utils import get_correlation_id_from_username, check_permissions_by_user
from shop.utils import get_all_shop_type, get_all_shop_category, search_shop
from web_admin import api_settings, setup_logger
from braces.views import GroupRequiredMixin
from django.views.generic.base import TemplateView
from django.shortcuts import render
from web_admin.get_header_mixins import GetHeaderMixin
from web_admin.utils import calculate_page_range_from_page_info

import logging

logger = logging.getLogger(__name__)

class ListView(GroupRequiredMixin, TemplateView, GetHeaderMixin):
    group_required = "CAN_MANAGE_SHOP"
    login_url = 'web:permission_denied'
    raise_exception = False
    template_name = 'shop/list.html'
    logger = logger

    def check_membership(self, permission):
        self.logger.info(
            "Checking permission for [{}] username with [{}] permission".format(self.request.user, permission))
        return check_permissions_by_user(self.request.user, permission[0])

    def dispatch(self, request, *args, **kwargs):
        correlation_id = get_correlation_id_from_username(self.request.user)
        self.logger = setup_logger(self.request, logger, correlation_id)
        return super(ListView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        permissions = {}
        permissions['CAN_ADD_SHOP'] = self.check_membership(["CAN_ADD_SHOP"])
        permissions['CAN_EDIT_SHOP'] = self.check_membership(["CAN_EDIT_SHOP"])
        permissions['CAN_DELETE_SHOP'] = self.check_membership(["CAN_DELETE_SHOP"])
        permissions['CAN_VIEW_SHOP'] = self.check_membership(["CAN_VIEW_SHOP"])
        form = request.GET
        context = {"form": form}
        self.logger.info('========== Start getting all shop types ==========')
        list_shop_type = get_all_shop_type(self)
        self.logger.info('========== Finish getting all shop types ==========')
        context['list_shop_type'] = list_shop_type

        self.logger.info('========== Start getting all shop categories ==========')
        list_shop_category = get_all_shop_category(self)
        self.logger.info('========== Finish getting all shop categories ==========')
        context['list_shop_category'] = list_shop_category
        opening_page_index = form.get('current_page_index', 1)

        params = {
            "paging": True,
            "page_index": int(opening_page_index)
        }
        if form.get('shop_id'):
            params['id'] = int(form['shop_id'])

        if form.get('shop_category'):
            params['shop_category_id'] = int(form['shop_category'])

        if form.get('shop_name'):
            params['name'] = form['shop_name']

        if form.get('shop_type'):
            params['shop_type_id'] = int(form['shop_type'])

        if form.get('relationship_manager'):
            params['relationship_manager_name'] = form['relationship_manager']

        if form.get('owner_id'):
            params['agent_id'] = form['owner_id']

        if form.get('mobile_device_unique_reference'):
            params['mobile_device_unique_reference'] = form['mobile_device_unique_reference']

        if form.get('edc_serial_number'):
            params['edc_serial_number'] = form['edc_serial_number']

        shops = search_shop(self, params)
        page = shops.get('page', {})
        context['permissions'] = permissions
        context.update({
            'shops': shops.get('shops', []),
            'paginator': page,
            'page_range': calculate_page_range_from_page_info(page),
            'total_result': page.get('total_elements', 0)
        })

        return render(request, self.template_name, context)


from PySide import QtCore
import pyqtgraph as pg
from pyqtgraph.graphicsItems.PlotItem import PlotItem
from pyqtgraph.graphicsItems.ViewBox import ViewBox
from pyqtgraph.graphicsItems.PlotDataItem import PlotDataItem

# local imports
from abstract_spectrum import AbstractSpectrum

# Use black text on white background
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

class SpectraPlotItem(PlotItem):

    def __init__(self, parent=None, name=None, labels=None,
                 title=None, viewBox=None, axisItems=None, enableMenu=True,
                 *spectra, **kwargs):
        '''
        Keyword Arguments
        -----------------
        xAxisView : str
            can be 'wavelength' (default) or 'energy'
        '''
        super(SpectraPlotItem, self).__init__(parent=None, name=None,
            labels=None, title=None, viewBox=None, axisItems=None,
            enableMenu=True, **kwargs)

        self._signalEnabled = True
        self._rawSignalEnabled = True
        self._phaseEnabled = True

        self._spectra = []
        self._signalLines = []
        self._rawSignalLines = []
        self._phaseLines = []

        # Define the color sequence
        self._colors = [(24, 90, 169),  # blue
                        (220, 40, 40),  # red
                        (0, 140, 72),  # green
                        (100, 44, 145),  # violet
                        (236, 110, 35),  # orange
                        ]

        # Setup axis, etc
        self._xAxisView = kwargs.get('xAxisView', 'wavelength')
        self._phaseViewBox = None
        self.showAxis('right')

        # Label the axes
        self.setLabel('left', 'Signal', 'V')
        self.setLabel('right', 'Phase', '°')
        self.updateXAxisLabel()

        # Add the spectra
        for spectrum in spectra:
            self.addSpectrum(spectrum)

    def setSignalEnabled(self, b):
        self._signalEnabled = bool(b)
        self.updateEnabled()

    def setRawSignalEnabled(self, b):
        self._rawSignalEnabled = bool(b)
        self.updateEnabled()

    def setPhaseEnabled(self, b):
        self._phaseEnabled = bool(b)
        self.updateEnabled()

    def updateEnabled(self):
        if self._signalEnabled:
            for line in self._signalLines:
                line.show()
        else:
            for line in self._signalLines:
                line.hide()
        if self._rawSignalEnabled:
            for line in self._rawSignalLines:
                line.show()
        else:
            for line in self._rawSignalLines:
                line.hide()
        if self._phaseEnabled:
            for line in self._phaseLines:
                line.show()
        else:
            for line in self._phaseLines:
                line.hide()

    def updateLogMode(self):
        x = self.ctrl.logXCheck.isChecked()
        y = self.ctrl.logYCheck.isChecked()
        for i in self.items:
            if hasattr(i, 'setLogMode'):
                i.setLogMode(x, y)
        self.getAxis('bottom').setLogMode(x)
        self.getAxis('top').setLogMode(x)
        self.getAxis('left').setLogMode(y)
        # self.getAxis('right').setLogMode(y)  # disable log mode for phase axis
        self.enableAutoRange()
        self.recomputeAverages()

    def updateXAxisLabel(self):
        if self._xAxisView == 'wavelength':
            self.setLabel('bottom', 'Wavelength (nm)', '')
        elif self._xAxisView == 'energy':
            self.setLabel('bottom', 'Energy', 'eV')

    def setXAxisView(self, s):
        self._xAxisView = s
        self.updateXAxisLabel()
        self.updateLines()

    def _getPhaseViewBox(self):
        if self._phaseViewBox is None:
            # Initialize it
            self._phaseViewBox = ViewBox()
            self.scene().addItem(self._phaseViewBox)
            self.getAxis('right').linkToView(self._phaseViewBox)
            self._phaseViewBox.setXLink(self)
            self.updateViews()
            self.vb.sigResized.connect(self.updateViews)
        return self._phaseViewBox

    def updateViews(self):
        # View has resized; update auxiliary views to match
        self._phaseViewBox.setGeometry(self.vb.sceneBoundingRect())

        # need to re-update linked axes since this was called
        # incorrectly while views had different shapes.
        # (probably this should be handled in ViewBox.resizeEvent)
        self._phaseViewBox.linkedViewChanged(self.vb,
                                             self._phaseViewBox.XAxis)

    def getNextColor(self):
        usedColors = [spectrum.getColor() for spectrum in self._spectra]
        unusedColors = [color for color in self._colors if
                        color not in usedColors]
        if unusedColors:
            return unusedColors[0]

        useCounts = [usedColors.count(color) for color in usedColors]
        minUsedColor = usedColors[useCounts.index(min(useCounts))]
        return minUsedColor

    @QtCore.Slot(AbstractSpectrum)
    def removeSpectrum(self, spectrum):
        if spectrum not in self._spectra:
            raise ValueError('spectrum not in plot')
        spectrum.sigChanged.disconnect(self.updateLines())
        i = self._spectra.index(spectrum)
        self._spectra.pop(i)
        self.removeItem(self._signalLines.pop(i))
        self.removeItem(self._rawSignalLines.pop(i))
        self._getPhaseViewBox().removeItem(self._phaseLines.pop(i))

    def clear(self):
        spectra = self._spectra[:]  # copy the list
        for spectrum in spectra:
            self.removeSpectrum(spectrum)

    def getX(self, spectrum):
        if self._xAxisView == 'wavelength':
            return spectrum.getWavelength()
        elif self._xAxisView == 'energy':
            return spectrum.getEnergy()
        else:
            raise ValueError('Unsupported value for xaxis: {}'
                             .format(self._xAxisView))

    @QtCore.Slot(AbstractSpectrum)
    def addSpectrum(self, spectrum):
        if spectrum in self._spectra:
            raise ValueError('spectrum alread in plot')

        color = self.getNextColor()
        spectrum.setColor(color)
        signalColor = pg.mkColor(color)
        rawSignalColor = signalColor.lighter()
        phaseColor = rawSignalColor.lighter(120)

        signalLine = self.plot(x=self.getX(spectrum),
                               y=spectrum.getSignal(),
                                  pen=pg.mkPen(signalColor))
        rawSignalLine = self.plot(x=self.getX(spectrum),
                                  y=spectrum.getRawSignal(),
                                  pen=pg.mkPen(rawSignalColor,
                                               style=QtCore.Qt.DashLine))
        phaseLine = PlotDataItem(x=self.getX(spectrum),
                                 y=spectrum.getPhase(),
                                 pen=pg.mkPen(phaseColor,
                                              style=QtCore.Qt.DotLine))
        self._getPhaseViewBox().addItem(phaseLine)
        self.updateEnabled()

        self._signalLines.append(signalLine)
        self._rawSignalLines.append(rawSignalLine)
        self._phaseLines.append(phaseLine)
        self._spectra.append(spectrum)
        spectrum.sigChanged.connect(self.updateLines)

    def updateLines(self):
        for spectrum, line in zip(self._spectra, self._signalLines):
            line.setData(x=self.getX(spectrum),
                         y=spectrum.getSignal())
        for spectrum, line in zip(self._spectra, self._rawSignalLines):
            line.setData(x=self.getX(spectrum),
                         y=spectrum.getRawSignal())
        for spectrum, line in zip(self._spectra, self._phaseLines):
            line.setData(x=self.getX(spectrum),
                         y=spectrum.getPhase())
        self.updateEnabled()


def partOne():
    gamma = 1
    epsilon = 1
    mydict = {}
    with open("input","r") as f:
        for line in f:
            bin_ = line.split()[0]
            #print(len(bin_))
            for idx,item in enumerate(bin_,1):
                #print(idx,item)
                if idx not in mydict:
                    mydict[idx] = [0,0]
                    #print(mydict)
                    if item == '0':
                        mydict[idx][0] = 1
                    else:
                        mydict[idx][1] = 1
                else:
                    if item == '0':
                        mydict[idx][0]+=1
                    else:
                        mydict[idx][1]+=1
    #print(mydict)

def get_lines():
    mylist=  []
    with open('input','r') as f:
        for line in f:
            lin = line.split()[0]
            mylist.append(lin)
    return mylist

def partTwo(data,oxygen,i):

    if len(data) == 1:
        return int(data[0],2)

    count1 = 0
    count0 = 0

    for line in data:
        if line[i] == '1':
            count1+=1
        else:
            count0+=1

    if oxygen:
        temp = '1' if count1>=count0 else '0'
    else:
        temp = '0' if count0<=count1 else '1'

    data = [x for x in data if x[i]==temp]

    return partTwo(data,oxygen,i+1)

if __name__ == "__main__":
    #partOne()
    mylist = []
    mylist = get_lines()
    o2 = partTwo(mylist,True,0)
    co2 = partTwo(mylist,False,0)
    print(o2*co2)


from django.contrib.auth import views as auth_views
from django.urls import path

from . import views

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(
        template_name="login.html",
        extra_context={'next': '/'},
        redirect_authenticated_user=True
    ),
         name="login"),
    path('register/', views.register, name='register'),
    path('logout/', views.logout_user, name='logout'),
]


import turtle, random
pen = turtle.Turtle()
pen.speed(100)
# turtle.bgcolor("black") # Change background color to black
pen.pensize(10000000)
pen.color("black")
pen.forward(10)
pen.pensize(4)
 # Algorithm -> Series of steps to take, to solve a problem.
for i in range(15):
    x = random.randint(-250, 250)
    y = random.randint(-250, 250)

    pen.up()
    pen.goto(x,y)
    pen.down()
    size = random.randint(50,300)

    colors = ["green", "red", "blue", "crimson", "maroon", "teal", "cyan", "pink", "purple", "salmon"]
    # aqua

    pen.color(random.choice(colors))
    for i in range(36):
        pen.forward(size)
        pen.backward(size)
        pen.left(10)

turtle.mainloop()


"""
Module for adminapp URLs.
"""
from django.urls import path

import adminapp.views as adminapp

app_name = 'adminapp'

urlpatterns = [
    # ========================================================================
    # User URLs
    # ========================================================================
    path(
        'users/',
        adminapp.UserListView.as_view(),
        name='users'
    ),
    path(
        'create_user/',
        adminapp.UserCreateView.as_view(),
        name='create_user'
    ),
    path(
        'read_user/<int:pk>/',
        adminapp.UserReadView.as_view(),
        name='read_user'
    ),
    path(
        'update_user/<int:pk>/',
        adminapp.UserUpdateView.as_view(),
        name='update_user'
    ),
    path(
        'delete_user/<int:pk>/',
        adminapp.UserDeleteView.as_view(),
        name='delete_user'
    ),
    # ========================================================================
    # Project URLs
    # ========================================================================
    path(
        'projects/',
        adminapp.ProjectListView.as_view(),
        name='projects'
    ),
    path(
        'create_project/',
        adminapp.ProjectCreateView.as_view(),
        name='create_project'
    ),
    # path(
    #     'read_project/',
    #     adminapp.ProjectDetailView.as_view(),
    #     name='read_project'
    # ),
    path(
        'update_project/<int:pk>/',
        adminapp.ProjectUpdateView.as_view(),
        name='update_project'
    ),
    path(
        'delete_project/<int:pk>/',
        adminapp.ProjectDeleteView.as_view(),
        name='delete_project'
    ),
    # ========================================================================
    # Category URLs
    # ========================================================================
    path(
        'categories/',
        adminapp.CategoryListView.as_view(),
        name='categories'
    ),
    path(
        'create_category/',
        adminapp.CategoryCreateView.as_view(),
        name='create_category'
    ),
    # path(
    #     'update_category/',
    #     adminapp.CategoryEditView.as_view(),
    #     name='update_category'
    # ),
    # path(
    #     'delete_category/',
    #     adminapp.CategoryDeleteView.as_view(),
    #     name='delete_category'
    # )
]