'''
1 Start with a random string of 28 characters.
2 Make 100 copies of the string (reproduce).
3 For each character in each of the 100 copies, with a probability of 5%, replace (mutate) the character with a new random character.
4 Compare each new string with the target string "METHINKS IT IS LIKE A WEASEL", and give each a score (the number of
  letters in the string that are correct and in the correct position).
5 If any of the new strings has a perfect score (28), halt. Otherwise, take the highest scoring string, and go to step 2.
'''

import random as rd
from PyQt5.QtWidgets import *
from PyQt5 import QtGui

class ScrollMessageBox(QMessageBox): #Funcao do scroll message box
   def __init__(self, l, *args, **kwargs):
      QMessageBox.__init__(self, *args, **kwargs)
      scroll = QScrollArea(self)
      scroll.setWidgetResizable(True)
      self.content = QWidget()
      scroll.setWidget(self.content)
      lay = QVBoxLayout(self.content)
      for item in l:
         lay.addWidget(QLabel(item, self)) #Adiciona os itens a caixa
      self.layout().addWidget(scroll, 0, 0, 1, self.layout().columnCount())
      self.setStyleSheet("QScrollArea{min-width:500 px; min-height: 600px}")
      self.setWindowTitle('Resultado')

class Weasel(QWidget):

    def __init__(self):
        super().__init__()

#       ============CRIACAO DOS LABELS, CAIXA DE TEXTO E BOTOES========
        taxa = QLabel('Taxa de mutação: ')
        numero_copia = QLabel('Copia por geração: ')
        frase = QLabel('Frase desejada: ')
        go_button = QPushButton("Go!", self)

        self.taxaEdit = QLineEdit("5")
        self.numeroEdit = QLineEdit("1000")
        self.fraseEdit = QLineEdit("ME THINKS IT IS LIKE A WEASEL")
        go_button.clicked.connect(self.buttonClicked)

#       ==============FORMATACAO======================
        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(taxa, 1, 0)
        grid.addWidget(self.taxaEdit, 1, 1)

        grid.addWidget(numero_copia, 2, 0)
        grid.addWidget(self.numeroEdit, 2, 1)

        grid.addWidget(frase, 3, 0)
        grid.addWidget(self.fraseEdit, 3, 1)

        grid.addWidget(go_button)
        self.setLayout(grid)
#       ================================================

        self.setGeometry(300, 300, 350, 300) #Tamanho
        self.setWindowTitle('Weasel') #Titulo
        self.show() #Mostrar

    def buttonClicked(self): #QUANDO O BOTAO FOR CLICADO

#       =================================FUNCOES=============================
        # copia[0] = copia da frase
        # copia[1] = nota da frase
        def iniciar_copia(copias, n_copias):
            for i in range(n_copias):
                copias[0].append("")  # Inicia o vetor da copia
                copias[1].append(0)  # Nota da iteracao, por enquanto se deixa 0

        # Copiar a string nas copias, pois se aplicara a mutacao em seguida
        def gerar_nova_copia(copias, string_copiada):
            for i in range(len(copias[0])):
                copias[0][i] = string_copiada

        #Substitui o caracter de uma frase
        def recolocar(frase, caracter, pos):
            temp = list(frase)
            temp[pos] = caracter

            return "".join(temp)

        # Atribuir uma nota a uma string
        def atribuir_nota_string(string, original):
            nota = 0
            for i in range(len(string)):
                if string[i] == original[i]:
                    nota += 1
            return nota

        # Encontrar o index da maior nota da lista
        def encontrar_index_maior_nota(copias):
            max = 0
            for i in range(len(copias[1])):
                if copias[1][i] > max:
                    max = i

            return max

        # Aplicar uma mutacao a todas as copias
        def aplicar_mutacao_e_nota(copias, string_desejado):
            for i in range(len(copias[0])):
                for j in range(len(copias[0][0])):
                    chance_mutacao = rd.random() * 100  # numero entre 0 e 100
                    if chance_mutacao < taxa_mutacao:  # Mutacao ocorre

                        # Se mutacao acontecer, ele pega um caracter aleatorio e substitui
                        copias[0][i] = recolocar(copias[0][i], candidatos[int(rd.random() * len(candidatos))], j)

                copias[1][i] = atribuir_nota_string(copias[0][i], string_desejado) #Dar uma nota

#       =====================================================================

        # Por centagem de mutacao
        taxa_mutacao = float(self.taxaEdit.text()) #Pega o texto da caixa de texto

        # String desejada
        string_desejado = self.fraseEdit.text() #Pega o texto da caixa de texto

        # Numero de copias por geracao
        n_copia = int(self.numeroEdit.text()) #Pega o texto da caixa de texto

        # Candidatos para se usar na string inicial aleatoria
        candidatos = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "

        rd.seed()

        string_inicial = ""

        # Gera um numero entre 0 e o tamanho da string desejada
        # Usando como base os candidatos, ele pega o numero gerado para criar uma string inicial aleatoria
        for i1 in range(len(string_desejado)):
            string_inicial += candidatos[int(rd.random() * len(candidatos))]

        copia = [[], []]

        # Inicia a matriz de copia
        iniciar_copia(copia, n_copia)

        # A string da geracao sera a string com maior nota
        string_geracao = string_inicial

        lista_geracao = [[], [], []]  # Criar a lista da geracao para o resultado

        lista_geracao[0].append(string_inicial)  # String da geracao 0
        lista_geracao[1].append(0)  # Numero da Geracao 0
        lista_geracao[2].append(atribuir_nota_string(string_inicial, string_desejado))  # Nota da string dessa geracao

        #Loop que so acabara quando a nota da copia for perfeita
        while(True):
            gerar_nova_copia(copia, string_geracao) #Gero uma nova copia com a string selecionada

            aplicar_mutacao_e_nota(copia, string_desejado) #Aplica-se uma mutacao a ela e da uma nota ao mutado

            string_geracao = copia[0][encontrar_index_maior_nota(copia)] #Uma nova string da geracao sera selecionado

            lista_geracao[0].append(string_geracao) #Adicionar a string da geracao na lista
            lista_geracao[1].append(max(lista_geracao[1]) + 1) #Dar um nome a geracao, no caso, ultima geracao + 1
            lista_geracao[2].append(atribuir_nota_string(string_geracao, string_desejado))

            if atribuir_nota_string(string_geracao, string_desejado) == len(string_desejado): #Se a nota do string atual == string desejado
                break

        listaprint = []
        # Print das geracoes
        for i in range(len(lista_geracao[0])):
            listaprint.append("Geracao [" + str(lista_geracao[1][i]) + "]: " + str(lista_geracao[0][i]) + ", Nota: [" + str(lista_geracao[2][i]) + "]")

#        Printar o resultado em um scrollbox
        result = ScrollMessageBox(listaprint, None)

#        Janela so fecha quando usuario clicar
        result.exec_()

#=======================MAIN==========================

#Iniciar uma aplicacao
app = QApplication([])
#Iniciar o programa "weasel"
ex = Weasel()
#Fechar apenas com o clique do usuario
app.exec_()

Weasel/Weasel - Daniel, Paulo, Miguel/Weasel.py


import json, os
from cygnus import groupme, utils

def init():
    if not os.path.exists("./cygnus/plugins/alias/"):
        os.makedirs("./cygnus/plugins/alias/")
    return

def parse(obj, me):
    text = obj["text"]
    work = text.split(" ")

    if '/alias' == work[0]:
        mentions = utils.get_mentions(obj)

        if "+me" in text:
            mentions.append(obj["user_id"])

        if mentions:
            alias_name = work[1].split("@")[0].lower()

            if os.path.isfile("./cygnus/plugins/alias/%s.json" % (obj["group_id"])):
                with open("./cygnus/plugins/alias/%s.json" % (obj["group_id"]), "r") as f:
                    aliases = json.load(f)
            else:
                aliases = {}

            aliases[alias_name] = mentions

            with open("./cygnus/plugins/alias/%s.json" % (obj["group_id"]), "w") as f:
                json.dump(aliases, f)

            groupme.send_message(obj, "Alias %s created." % (alias_name))
    elif "@" in text:
        key = text.split("@")[1].split(" ")[0].lower()

        if key == "everyone":
            return

        if os.path.isfile("./cygnus/plugins/alias/%s.json" % (obj["group_id"])):
                with open("./cygnus/plugins/alias/%s.json" % (obj["group_id"]), "r") as f:
                    aliases = json.load(f)
        else:
            return

        if key in aliases:
            mentions = aliases[key]
        else:
            return

        attachments = [
            {
                "type" : "mentions",
                "user_ids" : mentions,
                "loci" : [[0, len(text)]]*len(mentions)
            }
        ]

        groupme.send_message(obj, text, attachments)


import h5py
import numpy as np
import simulation as sim
from static_mesh import StaticMesh

class MovingMesh(StaticMesh):
    """
    moving mesh simulation class
    """

    def __init__(self, gamma = 1.4, CFL = 0.5, max_steps=100, max_time=None, output_cycle = 100000,
            output_name="simulation_", regularization=True):

        super(MovingMesh, self).__init__(gamma, CFL, max_steps, max_time, output_cycle, output_name)

        # simulation parameters
        self.regularization = regularization

    def get_dt(self):
        """
        Calculate the time step using the CFL condition.
        """

        vol = self.cells_info["volume"]

        # moving mesh solvers have different courant restraint depending if solved
        # in lab or moving frame
        self.dt = self.CFL*self.riemann_solver.get_dt(self.fields, vol, self.gamma)

        # correct time step if exceed max time
        if self.time + self.dt > self.max_time:
            self.dt = self.max_time - self.time

    def solve_one_step(self):
        """
        Evolve the simulation for one time step.
        """

        # generate ghost particles with links to original real particles
        self.particles = self.fields.update_boundaries(self.particles, self.particles_index, self.graphs)

        # construct the new mesh
        self.graphs = self.mesh.tessellate(self.particles)

        # calculate volume and center of mass of real particles
        self.cells_info, faces_info = self.mesh.cell_and_faces_info(self.particles, self.particles_index, self.graphs)

        # calculate primitive variables of real particles and pass to ghost particles with give boundary conditions
        self.fields.update_primitive(self.cells_info["volume"], self.particles, self.particles_index)

        # calculate global time step
        self.get_dt()

        # assign fluid velocities to particles, regularize if needed, and pass to ghost particles
        w = self.mesh.assign_particle_velocities(self.particles, self.fields, self.particles_index, self.cells_info, self.gamma, self.regularization)

        # assign face velocities
        self.mesh.assign_face_velocities(self.particles, self.particles_index, self.graphs, faces_info, w)

        # calculate gradient for real particles and pass to ghost particles
        #self.reconstruction.gradient(self.fields.prim, self.particles, self.particles_index, self.cells_info, self.graphs)

        # extrapolate state to face, apply frame transformations, solve riemann solver, and transform back
        fluxes = self.riemann_solver.fluxes(self.particles, self.particles_index, self.graphs, self.fields.prim, self.cells_info,
                faces_info, self.gamma, self.dt)

        # update conserved variables
        self.update(self.fields, fluxes, faces_info)

        # update particle positions
        self.move_particles(w)

    def move_particles(self, w):
        """
        advance real particles positions for one time step
        """
        self.particles[:,self.particles_index["real"]] += self.dt*w[:, self.particles_index["real"]]


##Problem Name : Leetcode Week 2 problem
## Problem  Name: Valid Perfect Square
##Time 32 ms
class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        i = 1
        the_sum = 0
        while the_sum < num:
            the_sum += i
            if the_sum == num:
                return True
            i += 2
        return False

##Time 16 MS
##class Solution:
##    def isPerfectSquare(self, num: int) -> bool:
##        l = 1
##        r = num
##        while(r >= l):
##            mid = int((l + r) / 2)
##            if mid ** 2 == num:
##                return True
##            elif mid ** 2 > num:
##                r = mid - 1
##            else:
##                l = mid + 1
##        return False


# @Time   :2018/9/10 22:34
# @Author :YTL
# @File   :operation_excel.py

import openpyxl
from collections import Iterable
import os

class OperationExcel:
    '''操作excel的类'''

    def __init__(self, filename=None):
        if filename is None:
            self.filename = os.path.join(os.getcwd(), 'test.xlsx')
        else:
            self.filename = filename
        self.operation = openpyxl.load_workbook(filename=self.filename)

    def write_header(self, header, sheet_name=None):
        if sheet_name is None or sheet_name == "":
            sheet_name = self.operation.sheetnames[0]
        sheet = self.operation[sheet_name]
        if isinstance(header, Iterable):
            for col, val in enumerate(header, 1):
                sheet.cell(row=1, column=col, value=val)
            self.operation.save(self.filename)
            print('write header success.')

    def write_line(self, data, sheet_name=None):
        if sheet_name is None or sheet_name == "":
            sheet_name = self.operation.sheetnames[0]
        sheet = self.operation[sheet_name]
        col_num = sheet.max_column

        if not isinstance(data, Iterable):
            print('data format is wrong.')
            return

        if len(data) != col_num:
            print('data length inconsistency.')
            return

        sheet.append(data)
        self.operation.save(self.filename)
        print('write line success.')

if __name__ == '__main__':
    header = ['header1', 'header2', 'header3', 'header4', 'header5']
    data = ['header1', 'header2', 'header3', 'header4', 'header5']
    op = OperationExcel()
    #op.write_header(header)
    op.write_line(data, 'Sheet1')
    op.write_line(data, 'Sheet1')


from keras.models import Model
from keras.layers import Input, Dense, Dropout, BatchNormalization, concatenate
from keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D

class GoogLeNet(Model):
    def __init__(self):
        super().__init__()

        input = Input(shape=(224, 224, 3))
        layer = self.Conv2d_BN(input, 64, (7, 7), strides=(2, 2), padding='same')
        layer = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(layer)
        layer = self.Conv2d_BN(layer, 192, (3, 3), strides=(1, 1), padding='same')
        layer = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(layer)
        layer = self.Inception(layer, 64)  # 256
        layer = self.Inception(layer, 120)  # 480
        layer = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(layer)
        layer = self.Inception(layer, 128)  # 512
        layer = self.Inception(layer, 128)
        layer = self.Inception(layer, 128)
        layer = self.Inception(layer, 132)  # 528
        layer = self.Inception(layer, 208)  # 832
        layer = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(layer)
        layer = self.Inception(layer, 208)
        layer = self.Inception(layer, 256)  # 1024
        layer = AveragePooling2D(pool_size=(7, 7), strides=(7, 7), padding='same')(layer)
        layer = Dropout(0.4)(layer)
        layer = Dense(1000, activation='relu')(layer)
        layer = Dense(1000, activation='softmax')(layer)

        model = Model(input, layer, name='Inception')

        model.compile(loss='categorical_crossentropy', optimizer='SGD', metrics=['accuracy'])
        model.summary()

    def Conv2d_BN(self, layer, nb_filter, kernel_size, padding='same', strides=(1, 1), name=None):
        if name is not None:
            bn_name = name + '_bn'
            conv_name = name + '_conv'
        else:
            bn_name = None
            conv_name = None

        layer = Conv2D(nb_filter, kernel_size, padding=padding, strides=strides, activation='relu', name=conv_name)(
            layer)
        layer = BatchNormalization(axis=3, name=bn_name)(layer)

        return layer

    def Inception(self, layer, nb_filter):
        branch1x1 = self.Conv2d_BN(layer, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)

        branch3x3 = self.Conv2d_BN(layer, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
        branch3x3 = self.Conv2d_BN(branch3x3, nb_filter, (3, 3), padding='same', strides=(1, 1), name=None)

        branch5x5 = self.Conv2d_BN(layer, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
        branch5x5 = self.Conv2d_BN(branch5x5, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)

        branchpool = MaxPooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(layer)
        branchpool = self.Conv2d_BN(branchpool, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)

        layer = concatenate([branch1x1, branch3x3, branch5x5, branchpool], axis=3)

        return layer


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 16:53:24 2020

@author: sushila.sipai
"""

import cx_Oracle

ip='10.2.3.21'
sid='DANPHE'
port='1521'

try:
   dns_tns=cx_Oracle.makedsn(ip,port,sid)
   db=cx_Oracle.connect('system','manager',dns_tns)

except :
   print('Connection Failed')
db.autocommit=True

mesg_req_type=['1200', '1420','1220','1804']
mesg_type=['1210', '1430','1230','1814']
with open ('LISRVR_NPS_SWIF_119993_240220_08.log', 'r') as fo :

   mesg=[]
   i=0
   flg=False
   mesg.append([])

   for line in fo:
         if "MessageId" in line.strip():
            if((line.partition(':')[2]).strip() in (mesg_type)):
                flg=True
            mesg[i].append((line.partition(':')[2]).strip())
         elif "Field 003" in line.strip():
            mesg[i].append((line.partition(':')[2]).strip())
         elif "Field 011" in line.strip():
            mesg[i].append((line.partition(':')[2]).strip())
         elif "Field 017" in line.strip():
           mesg[i].append((line.partition(':')[2]).strip())
         elif "Field 039" in line.strip():
           mesg[i].append((line.partition(':')[2]).strip())
           if(flg==True):
               i+=1
               mesg.append([])
               flg=False
           else:
            pass
   print(len(mesg))
   print (mesg)

updatecount=0
zeroappendcount=0
for n in range(len(mesg)):
    if(len(mesg[n])!=9):
        print (n)
        print (len(mesg[n]))
        if(len(mesg[n]) >0):
            if(mesg  [n][0] in (mesg_type)):
                cursor1=db.cursor()
                cursor1.execute("select QFIELD011 from custom.c24logs where QFIELD003='%s' and qfield011='%s' and qfield017='%s'"%(mesg[n][1],mesg[n][2],mesg[n][3]))
                if(len(cursor1.fetchall())> 0):
                    cursor2=db.cursor()
                    cursor2.execute("update custom.c24logs set rmessageid='%s', rfield003='%s', rfield011='%s', rfield017='%s', rfield039='%s' where QFIELD003='%s' and qfield011='%s' and qfield017='%s'"%(mesg[n][0],mesg[n][1],mesg[n][2],mesg[n][3],mesg[n][4],mesg[n][1],mesg[n][2],mesg[n][3]))
                    updatecount+=1
                print ("updated")
                print(mesg[n])
            elif(mesg[n][0] in mesg_req_type):
                for j in range(len(mesg[n]),9):
                    mesg[n].append(0)
                zeroappendcount+=1
                print("zero appended")
                print(mesg[n])
        print("update count and zero append count:")
        print(updatecount)
        print(zeroappendcount)

cursor=db.cursor()
insertfail=0
for n in range(len(mesg)):
    if(len(mesg[n])==9):
        cursor.execute("Insert into custom.c24logs (qMessageId,qField003,qField011,qField017,rMessageId,rField003,rField011,rField017,rField039) values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" %(mesg[n][0],mesg[n][1],mesg[n][2],mesg[n][3],mesg[n][4],mesg[n][5],mesg[n][6],mesg[n][7],mesg[n][8]))
    else:
        insertfail+=1
        print ("failed to insert")
        print(mesg[n])
print("inset fail count:")
print(insertfail)


from collections import defaultdict
import math
n = list(input())
answer = 0
dict = defaultdict(int)

for i in range(len(n)):
    if n[i] == "6" or n[i] == "9":
        dict["6"] += 1
    else:
        dict[n[i]] += 1
dict["6"] = int(math.ceil(dict["6"]/2))

sorted_dict = sorted(dict.items(), key=lambda x : -x[1])
print(sorted_dict[0][1])


import tornado.ioloop
from tornado.web import RequestHandler, Application
import json

class FormHandler(RequestHandler):
    def get(self):
        print(dir(self))
        self.write(open('indexForm.html').read())

    def post(self):
        self.set_header("Content-Type", "application/json")
        self.write(
            json.dumps({
                'data': self.get_body_argument("message"),
            })
        )

def main():
    return Application([
        (r'/', FormHandler),
    ])

if __name__ == "__main__":
    app = main()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()


import numpy as np
from random import shuffle
from dash.sn_processing import PreProcessing
from dash.combine_sn_and_host import CombineSnAndHost
import multiprocessing as mp
import random
import time

class AgeBinning(object):
    def __init__(self, minAge, maxAge, ageBinSize):
        self.minAge = minAge
        self.maxAge = maxAge
        self.ageBinSize = ageBinSize

    def age_bin(self, age):
        ageBin = int(round(age / self.ageBinSize)) - int(round(self.minAge / self.ageBinSize))

        return ageBin

    def age_labels(self):
        ageLabels = []

        ageBinPrev = 0
        ageLabelMin = self.minAge
        for age in np.arange(self.minAge, self.maxAge, 0.5):
            ageBin = self.age_bin(age)

            if ageBin != ageBinPrev:
                ageLabelMax = int(round(age))
                ageLabels.append(str(int(ageLabelMin)) + " to " + str(ageLabelMax))
                ageLabelMin = ageLabelMax

            ageBinPrev = ageBin

        ageLabels.append(str(int(ageLabelMin)) + " to " + str(int(self.maxAge)))

        return ageLabels

class CreateLabels(object):

    def __init__(self, nTypes, minAge, maxAge, ageBinSize, typeList, hostList, nHostTypes):
        self.nTypes = nTypes
        self.minAge = minAge
        self.maxAge = maxAge
        self.ageBinSize = ageBinSize
        self.typeList = typeList
        self.ageBinning = AgeBinning(self.minAge, self.maxAge, self.ageBinSize)
        self.numOfAgeBins = self.ageBinning.age_bin(self.maxAge-0.1) + 1
        self.nLabels = self.nTypes * self.numOfAgeBins
        self.ageLabels = self.ageBinning.age_labels()
        self.hostList = hostList
        self.nHostTypes = nHostTypes

    def label_array(self, ttype, age, host=None):
        ageBin = self.ageBinning.age_bin(age)

        try:
            typeIndex = self.typeList.index(ttype)
        except ValueError as err:
            print("INVALID TYPE: {0}".format(err))
            raise ValueError

        if host is None:
            labelArray = np.zeros((self.nTypes, self.numOfAgeBins))
            labelArray[typeIndex][ageBin] = 1
            labelArray = labelArray.flatten()
            typeName = ttype + ": " + self.ageLabels[ageBin]
        else:
            hostIndex = self.hostList.index(host)
            labelArray = np.zeros((self.nHostTypes, self.nTypes, self.numOfAgeBins))
            labelArray[hostIndex][typeIndex][ageBin] = 1
            labelArray = labelArray.flatten()
            typeName = "{}: {}: {}".format(host, ttype, self.ageLabels[ageBin])

        labelIndex = np.argmax(labelArray)

        return labelIndex, typeName

    def type_names_list(self):
        typeNamesList = []
        if self.hostList is None:
            for tType in self.typeList:
                for ageLabel in self.ageBinning.age_labels():
                    typeNamesList.append("{}: {}".format(tType, ageLabel))
        else:
            for host in self.hostList:
                for tType in self.typeList:
                    for ageLabel in self.ageBinning.age_labels():
                        typeNamesList.append("{}: {}: {}".format(host, tType, ageLabel))

        return typeNamesList

class TempList(object):
    def temp_list(self, tempFileList):
        f = open(tempFileList, 'rU')

        fileList = f.readlines()
        for i in range(0,len(fileList)):
            fileList[i] = fileList[i].strip('\n')

        f.close()

        return fileList

class ReadSpectra(object):

    def __init__(self, w0, w1, nw, snFilename, galFilename=None):
        self.w0 = w0
        self.w1 = w1
        self.nw = nw
        self.snFilename = snFilename
        if galFilename is None:
            self.data = PreProcessing(snFilename, w0, w1, nw)
        else:
            self.galFilename = galFilename
            self.dataCombined = CombineSnAndHost(snFilename, galFilename, w0, w1, nw)

    def sn_plus_gal_template(self, snAgeIdx, snCoeff, galCoeff, z):
        wave, flux, minIndex, maxIndex, nCols, ages, tType = self.dataCombined.training_template_data(snAgeIdx, snCoeff, galCoeff, z)

        return wave, flux, nCols, ages, tType, minIndex, maxIndex

    def snid_template_data(self, ageIdx, z):
        """ lnw template files """
        wave, flux, nCols, ages, tType, minIndex, maxIndex = self.data.snid_template_data(ageIdx, z)

        return wave, flux, nCols, ages, tType, minIndex, maxIndex

    def sf_age(self):
        snName, extension = self.snFilename.strip('.dat').split('.')
        ttype, snName = snName.split('/')

        if extension == 'max':
            age = 0
        elif extension[0] == 'p':
            age = float(extension[1:])
        elif extension[0] == 'm':
            age = -float(extension[1:])
        else:
            print("Invalid Superfit Filename: " + self.snFilename)

        return snName, ttype, age

    def superfit_template_data(self, z):
        """ Returns wavelength and flux after all preprocessing """
        wave, flux, minIndex, maxIndex = self.data.two_column_data(z, minWave=self.w0, maxWave=self.nw)
        snName, ttype, age = self.sf_age()

        print(snName, ttype, age)

        return wave, flux, minIndex, maxIndex, age, snName, ttype

    def input_spectrum(self, z, smooth, minWave, maxWave):
        wave, flux, minIndex, maxIndex = self.data.two_column_data(z, smooth, minWave, maxWave)

        return wave, flux, int(minIndex), int(maxIndex)

class ArrayTools(object):

    def __init__(self, nLabels, nw):
        self.nLabels = nLabels
        self.nw = nw

    def shuffle_arrays(self, images, labels, filenames, typeNames):
        arraySize = len(labels)
        imagesShuf = np.empty((arraySize, int(self.nw)), np.float16)
        labelsShuf = np.empty(arraySize, np.uint16)
        filenamesShuf = np.empty(arraySize, dtype=object)
        typeNamesShuf = np.empty(arraySize, dtype=object)
        idx = 0
        print("Shuffle2")
        # Randomise order
        indexShuf = list(range(arraySize))
        shuffle(indexShuf)
        for i in indexShuf:
            imagesShuf[idx] = images[i]
            labelsShuf[idx] = labels[i]
            filenamesShuf[idx] = filenames[i]
            typeNamesShuf[idx] = typeNames[i]
            idx += 1
        print("LenLabels")
        print(len(labels), idx)

        print(imagesShuf)
        print(typeNamesShuf)
        print("Shuffle3")
        return imagesShuf, labelsShuf, filenamesShuf, typeNamesShuf

    def count_labels(self, labels):
        counts = np.zeros(self.nLabels)

        for i in range(len(labels)):
            counts[labels[i]] += 1

        return counts

    def div0(self, a, b):
        """ ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] """
        with np.errstate(divide='ignore', invalid='ignore'):
            c = np.true_divide(a, b)
            c[~ np.isfinite(c)] = 0  # -inf inf NaN
        return c

    def over_sample_arrays(self, images, labels, filenames, typeNames):
        counts = self.count_labels(labels)
        idx = 0
        print("Before OverSample")  #
        print(counts)  #

        overSampleAmount = self.div0(1 * max(counts), counts)  # ignore zeros in counts
        overSampleArraySize = int(sum(np.array(overSampleAmount, int) * counts))
        print(np.array(overSampleAmount, int) * counts)
        print(np.array(overSampleAmount, int))
        print(overSampleArraySize, len(labels))
        imagesOverSampled = np.zeros((overSampleArraySize, int(self.nw)), np.float16)
        labelsOverSampled = np.zeros(overSampleArraySize, np.uint16)
        filenamesOverSampled = np.empty(overSampleArraySize, dtype=object)
        typeNamesOverSampled = np.empty(overSampleArraySize, dtype=object)

        counts1 = np.zeros(self.nLabels)

        imagesShuf, labelsShuf, filenamesShuf, typeNamesShuf = self.shuffle_arrays(images, labels, filenames, typeNames)
        print(len(labelsShuf))
        for i in range(len(labelsShuf)):
            label = labelsShuf[i]
            image = imagesShuf[i]
            filename = filenamesShuf[i]
            typeName = typeNamesShuf[i]

            labelIndex = label # np.argmax(label)

            print(idx, i, int(overSampleAmount[labelIndex]))
            for r in range(int(overSampleAmount[labelIndex])):
                imagesOverSampled[idx] = image #np.concatenate(imagesOverSampled, np.array([image]), axis=0)
                labelsOverSampled[idx] = label #np.concatenate(labelsOverSampled, np.array([label]), axis=0)
                filenamesOverSampled[idx] = filename #filenamesOverSampled = np.append(filenamesOverSampled, filename)
                typeNamesOverSampled[idx] = typeName #typeNamesOverSampled = np.append(typeNamesOverSampled, typeName)
                counts1[labelIndex] += 1
                idx += 1

        print("After OverSample")  #
        print(counts1)  #

        print("Before Shuffling")
        imagesOverSampledShuf, labelsOverSampledShuf, filenamesOverSampledShuf, typeNamesOverSampledShuf = self.shuffle_arrays(imagesOverSampled, labelsOverSampled, filenamesOverSampled, typeNamesOverSampled)
        print("After Shuffling")
        return imagesOverSampledShuf, labelsOverSampledShuf, filenamesOverSampledShuf, typeNamesOverSampledShuf

class CreateArrays(object):
    def __init__(self, w0, w1, nw, nTypes, minAge, maxAge, ageBinSize, typeList, minZ, maxZ, redshiftPrecision, hostTypes=None, nHostTypes=None):
        self.w0 = w0
        self.w1 = w1
        self.nw = nw
        self.nTypes = nTypes
        self.minAge = minAge
        self.maxAge = maxAge
        self.ageBinSize = ageBinSize
        self.typeList = typeList
        self.minZ = minZ
        self.maxZ = maxZ
        self.numOfRedshifts = (maxZ - minZ) * 1./redshiftPrecision
        self.ageBinning = AgeBinning(minAge, maxAge, ageBinSize)
        self.numOfAgeBins = self.ageBinning.age_bin(maxAge-0.1) + 1
        self.nLabels = nTypes * self.numOfAgeBins * nHostTypes
        self.createLabels = CreateLabels(self.nTypes, self.minAge, self.maxAge, self.ageBinSize, self.typeList, hostTypes, nHostTypes)
        self.hostTypes = hostTypes

    def snid_templates_to_arrays(self, snidTemplateLocation, tempfilelist):
        """ This function is for the SNID processed files, which
            have been preprocessed to negatives, and so cannot be
            imaged yet """

        tempList = TempList().temp_list(tempfilelist) #Arbrirary redshift to read filelist
        typeList = []
        images = np.empty((0, int(self.nw)), np.float16)  # Number of pixels
        labelsIndexes = [] # labels = np.empty((0, self.nLabels), np.uint8)  # Number of labels (SN types)
        filenames = []#np.empty(0)
        typeNames = []#np.empty(0)
        agesList = []

        for i in range(0, len(tempList)):
            ncols = 15
            readSpectra = ReadSpectra(self.w0, self.w1, self.nw, snidTemplateLocation + tempList[i])

            for ageidx in range(0, 1000):
                if ageidx < ncols:
                    for z in np.linspace(self.minZ, self.maxZ, self.numOfRedshifts + 1):
                        tempwave, tempflux, ncols, ages, ttype, tminindex, tmaxindex = readSpectra.snid_template_data(ageidx, z)
                        agesList.append(ages[ageidx])
                        if not tempflux.any():
                            print("NO DATA for {} ageIdx:{} z>={}".format(tempList[i], ageidx, z))
                            break

                        if self.minAge < float(ages[ageidx]) < self.maxAge:
                            labelIndex, typeName = self.createLabels.label_array(ttype, ages[ageidx])
                            nonzeroflux = tempflux[tminindex:tmaxindex + 1]
                            newflux = (nonzeroflux - min(nonzeroflux)) / (max(nonzeroflux) - min(nonzeroflux))
                            newflux2 = np.concatenate((tempflux[0:tminindex], newflux, tempflux[tmaxindex + 1:]))
                            images = np.append(images, np.array([newflux2]), axis=0)  # images.append(newflux2)
                            labelsIndexes.append(labelIndex) # labels = np.append(labels, np.array([label]), axis=0)  # labels.append(ttype)
                            filenames.append(tempList[i] + '_' + ttype + '_' + str(ages[ageidx]) + '_z' + str(z))
                            typeNames.append(typeName)

                    print(tempList[i], ageidx, ncols)
                else:
                    break

            # Create List of all SN types
            if ttype not in typeList:
                typeList.append(ttype)
        print(len(images))

        try:
            print("SIZE OF ARRAYS:")
            print(images.nbytes)
            print(np.array(labelsIndexes).nbytes)
            print(np.array(filenames).nbytes)
            print(np.array(typeNames).nbytes)
        except:
            print("Exception Raised")

        return typeList, images, np.array(labelsIndexes), np.array(filenames), np.array(typeNames)

    def combined_sn_gal_templates_to_arrays(self, snTemplateLocation, snTempFileList, galTemplateLocation, galTempList):
        snTempList = TempList().temp_list(snTempFileList)
        typeList = []
        images = np.empty((0, int(self.nw)), np.float16)  # Number of pixels
        labelsIndexes = [] # labels = np.empty((0, self.nLabels), np.uint8)  # Number of labels (SN types)
        filenames = []  # np.empty(0)
        typeNames = []  # np.empty(0)
        agesList = []
        for j in range(len(galTempList)):
            for i in range(0, len(snTempList)):
                ncols = 15
                readSpectra = ReadSpectra(self.w0, self.w1, self.nw, snTemplateLocation + snTempList[i], galTemplateLocation + galTempList[j])
                for ageidx in range(0, 1000):
                    if ageidx < ncols:
                        for snCoeff in [0.01, 0.02, 0.05, 0.07, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:
                            galCoeff = 1 - snCoeff
                            for z in np.linspace(self.minZ, self.maxZ, self.numOfRedshifts + 1):
                                tempwave, tempflux, ncols, ages, ttype, tminindex, tmaxindex = readSpectra.sn_plus_gal_template(ageidx, snCoeff, galCoeff, z)
                                agesList.append(ages[ageidx])
                                if not tempflux.any():
                                    print("NO DATA for {} {} ageIdx:{} z>={}".format(galTempList[j], snTempList[i], ageidx, z))
                                    break

                                if self.minAge < float(ages[ageidx]) < self.maxAge:
                                    if self.hostTypes is None: # Checks if we are classifying by host as well
                                        labelIndex, typeName = self.createLabels.label_array(ttype, ages[ageidx], host=None)
                                    else:
                                        labelIndex, typeName = self.createLabels.label_array(ttype, ages[ageidx], host=galTempList[j])
                                    nonzeroflux = tempflux[tminindex:tmaxindex + 1]
                                    newflux = (nonzeroflux - min(nonzeroflux)) / (max(nonzeroflux) - min(nonzeroflux))
                                    newflux2 = np.concatenate((tempflux[0:tminindex], newflux, tempflux[tmaxindex + 1:]))
                                    images = np.append(images, np.array([newflux2]), axis=0)
                                    labelsIndexes.append(labelIndex) # labels = np.append(labels, np.array([label]), axis=0)
                                    filenames.append("{0}_{1}_{2}_{3}_snCoeff{4}_z{5}".format(snTempList[i], ttype, str(ages[ageidx]), galTempList[j], snCoeff, (z)))
                                    typeNames.append(typeName)

                        print(snTempList[i], ageidx, ncols, galTempList[j], snCoeff)
                    else:
                        break

                # Create List of all SN types
                if ttype not in typeList:
                    typeList.append(ttype)
        print(len(images))

        try:
            print("SIZE OF ARRAYS:")
            print(images.nbytes)
            print(np.array(labelsIndexes).nbytes)
            print(np.array(filenames).nbytes)
            print(np.array(typeNames).nbytes)
        except:
            print("Exception Raised")

        return typeList, images, np.array(labelsIndexes), np.array(filenames), np.array(typeNames)

    def combined_sn_gal_arrays_multiprocessing(self, snTemplateLocation, snTempFileList, galTemplateLocation, galTempFileList):
        galTempList = TempList().temp_list(galTempFileList)

        images = np.empty((0, int(self.nw)), np.float16)
        labelsIndexes = np.empty(0, np.uint16)
        filenames = np.empty(0)
        typeNames = np.empty(0)

        t1 = time.time()
        pool = mp.Pool(processes=11)
        results = [pool.apply_async(self.combined_sn_gal_templates_to_arrays, args=(snTemplateLocation, snTempFileList, galTemplateLocation, [gList],)) for gList in galTempList]

        outputs = [p.get() for p in results]

        for out in outputs:
            typeList, imagesPart, labelsPart, filenamesPart, typeNamesPart = out
            images = np.append(images, imagesPart, axis=0)
            labelsIndexes = np.append(labelsIndexes, labelsPart, axis=0)
            filenames = np.append(filenames, filenamesPart)
            typeNames = np.append(typeNames, typeNamesPart)

        t2 = time.time()
        print("time spent: {0:.2f}".format(t2 - t1))

        try:
            print("SIZE OF ARRAYS:")
            print(images.nbytes)
            print(labelsIndexes.nbytes)
            print(filenames.nbytes)
            print(typeNames.nbytes)
        except:
            print("Exception Raised")

        return typeList, images, labelsIndexes, filenames, typeNames


import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

def hist2D_demo(image):
    hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
    hist = cv.calcHist([image], [0, 1], None, [180, 256], [0, 180, 0, 256])
    # cv.imshow('hist_2D', hist)
    plt.imshow(hist)
    plt.title('2D—Histogram')
    plt.show()

def break_projection_demo(sample, target):
    roi_hsv = cv.cvtColor(sample, cv.COLOR_BGR2HSV)
    target_hsv = cv.cvtColor(target, cv.COLOR_BGR2HSV)

    # show images
    cv.imshow('sample', sample)
    cv.imshow('target', target)

    roiHis = cv.calcHist([roi_hsv], [0, 1], None, [32, 32], [0, 180, 0, 256])
    cv.normalize(roiHis, roiHis, 0, 255, cv.NORM_MINMAX)  # 规划到 [0，255]
    dst = cv.calcBackProject([target_hsv], [0, 1], roiHis, [0, 180, 0, 256], 1)
    cv.imshow('calcBackProject', dst)

print('-----Hello Python------')
src = cv.imread('C:/Users/JIE/Desktop/illustration/picture/1.jpg')
src1 = cv.imread('C:/Users/JIE/Desktop/illustration/picture/1_test.jpg')
cv.namedWindow('input image', cv.WINDOW_AUTOSIZE)
cv.imshow('input image', src)
hist2D_demo(src)
break_projection_demo(src, src1)
cv.waitKey(0)
cv.destroyWindow()


import itertools,copy
import glob,os,sys
import time

sys.path.append(glob.glob(os.getcwd())[0] + "/../../day5/python")

from intcode import Intcode

def get_maximum_thrust(file_location):
  """ Goes through all permutations and checks the maximum thrust value. """

  max = -sys.maxsize
  for phase in itertools.permutations([0,1,2,3,4]):
    intcodes = [Intcode(file_location,[i],verbose=False) for i in phase]
    out = 0
    for intcode in intcodes:
      terminate,out = intcode(out)
      if out > max: max = out
  return max

def feedback_thrust(file_location):
  """ Goes through all permutations and returns the maximum feedback thrust. """

  max = -sys.maxsize

  for phase in itertools.permutations([5,6,7,8,9]):

    intcodes = [Intcode(file_location,[i],False,False) for i in phase]

    terminate,out = False,0

    while not terminate:
      for intcode in intcodes:
        terminate,out = intcode(out)
    if out > max:
      max = out
  return max

def main():

  file_location = "../data/input.csv"

  # Solve puzzle
  t0 = time.time()
  part_one = get_maximum_thrust(file_location)
  time_part_one = round((time.time()-t0)*1e3)
  print("Solution to part one: %s (time taken %s[ms])" % (
      part_one, time_part_one))

  t0 = time.time()
  part_two = feedback_thrust(file_location)
  time_part_two = round((time.time()-t0)*1e3)
  print("Solution to part two: %s (time taken %s[ms])" % (
      part_two, time_part_two))

if __name__=="__main__":
  main()


import time
import mediapipe as mp
import os
import cv2

class handDetector():
    def __init__(self,mode=False,is_authenticated=True,maxHands=2,detection_confidence=0.5,tracking_confidence=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detection_confidence= detection_confidence
        self.tracking_confidence = tracking_confidence
        self.mp_hands = mp.solutions.hands
        self.hands = self.mp_hands.Hands(self.mode,self.maxHands,self.detection_confidence,self.tracking_confidence)
        self.mp_draw= mp.solutions.drawing_utils

    def Find_hands(self, img, draw=True):
        img_RGB = cv2.cvtColor( img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(img_RGB)
        if self.results.multi_hand_landmarks:
            for hand_marks in self.results.multi_hand_landmarks:
               if draw:
                   self.mp_draw.draw_landmarks(img,hand_marks, self.mp_hands.HAND_CONNECTIONS )
        return img

    def Find_position(self, img, hand_no = 0, draw= True):
        self.land_mark_list =[]
        if self.results.multi_hand_landmarks:
            my_hand = self.results.multi_hand_landmarks[hand_no]
            for id, land_mark in enumerate(my_hand.landmark):
                 h,w,c = img.shape
                 center_x, center_y = int(land_mark.x*w), int(land_mark.y*h)
                 self.land_mark_list.append([id , center_x, center_y])
                 if draw:
                     cv2.circle(img, (center_x,center_y), 5, (255,55,55), cv2.FILLED)
        return self.land_mark_list

wCam , hCam = 640, 480
cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)

folder_path = "nu"
my_list = os.listdir(folder_path)
print(my_list)

over_lay_list=[]
for img_path in my_list:
    image = cv2.imread(f'{folder_path}/{img_path}')
    print(f'{folder_path}/{img_path}')
    over_lay_list.append(image)
    print(len(over_lay_list))

print(len(over_lay_list))
previous_time = 0

detector = handDetector(detection_confidence=0.5)
Tip_IDS= [4, 8,12, 16,20]

while True:
   success, img = cap.read()
   img = detector.Find_hands(img)
   landmark_List = detector.Find_position(img,draw = False)

   if len(landmark_List)!=0 :
       Figures = []

       #thumb
       if landmark_List[Tip_IDS[0]][1]>landmark_List[Tip_IDS[0]-1][1]:
             Figures.append(1)
       else :
           Figures.append(0)

    #for 4 fing
       for id in range(1,5):
           if landmark_List[Tip_IDS[id]][2]<landmark_List[Tip_IDS[id]-2][2]:
             Figures.append(1)
           else :
               Figures.append(0)
       total_figure= Figures.count(1)
       print(total_figure)

       h, w, c = over_lay_list[total_figure-0].shape
       img[0:h,0:w]=over_lay_list[total_figure-0]
       cv2.rectangle(img,(20,225),(170,425),(0,255,0),cv2.FILLED)
       cv2.putText(img, str(total_figure), (45,375), cv2.FONT_HERSHEY_PLAIN,10,(255,89,45),25)

   current_time = time.time()
   fps = 1 / (current_time-previous_time)
   previous_time = current_time
   cv2.putText(img, f'FPS: {int(fps)}',(400, 55), cv2.FONT_HERSHEY_PLAIN , 3, (255,12,12),3)

   cv2.imshow("Image",img)
   if cv2.waitKey(1) & 0xFF == ord('q'):
       break

cv2.destroyAllWindows()


# Christopher Mendoza
# February 18, 2016
# Section CSCI-UA.0002 12:30PM - 1:45PM
# Guess The Number Game (Problem 2)

import random

print("I'm thinking of a number between 1 and 10!")
count = 1
tries = 0
ran_number = random.randint(1,10)

while count <=3:
    count = count+1
    tries= tries+1
    number = int(input("What's your guess? "))

    if tries !=3:
        if number < ran_number:
            print("Too low, try again.")
        elif number > ran_number:
         print("Too high, try again.")

    if number == ran_number:
        break

if number == ran_number:
    print("You got it!")
    print("The secret number was", ran_number,".")
    if tries == 1:
        print("It took you",tries,"try to guess the number.")
    else:
        print("It took you",tries,"tries to guess the number.")
else:
    print("The secret number was", ran_number,".")
    print("You didn't guess the number.")


from selenium.webdriver import Firefox
from time import sleep # importando sleep para que o selenium espere antes de procurar em elemento

booklist = 'https://my-simple-book-list.herokuapp.com'

browser = Firefox()

browser.get(booklist)

# sleep(3)

botao = browser.find_element_by_tag_name('button')
botao.click()

sleep(1)
botaocancel = browser.find_element_by_class_name('cancel')

botaocancel.click()

# browser.quit()


from scipy.ndimage import affine_transform
import numpy as np
import nibabel as nib
from nilearn.plotting import plot_img
from matplotlib import pyplot as plt

# x = nib.load("Task04_Hippocampus/imagesTr/hippocampus_001.nii.gz")
# image = x.get_fdata()
# M = np.random.random((4,4))
# M[3] = [0,0,0,1]
# image_tr = affine_transform(image,M)
# new_image = nib.Nifti1Image(image_tr, affine=np.eye(4))
# new_image.to_filename("deformed.nii")
# plot_img("Task04_Hippocampus/imagesTr/hippocampus_001.nii.gz")
# plot_img("deformed.nii")
# plt.show()

image  = np.random.random((3,3,3))*100
image = np.around(image)
M = np.eye(4)
M[0][0] = 1.5

print("TRANSFORMATION MATRIX")
print(M)
print("")

image_tr = affine_transform(image,M, mode ="nearest")
print("INPUT IMAGE")
print(image)

print("")
print("OUTPUT IMAGE")
print(image_tr)

import cv2
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter

def elastic_transform(image,alpha, sigma):
    shape = image.shape
    random_state = np.random.RandomState(None)
    dx = gaussian_filter((random_state.rand(*shape)*2 - 1),sigma)*alpha
    dy = gaussian_filter((random_state.rand(*shape)*2 - 1),sigma)*alpha
    dz = np.zeros_like(dx)
    x,y,z = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), np.arange(shape[2]))
    indices = np.reshape(y + dy,(-1,1)),np.reshape(x + dx,(-1,1)), np.reshape(z,(-1,1))
    return map_coordinates(image,indices).reshape(shape)

# affine transformation
# elastic_transform


from socket import *
import os
import threading
import sys
from termcolor import colored   #for highlighting
import logging

#now we will Create and configure logger
logging.basicConfig(filename="proxy.log",
					format='%(asctime)s %(message)s',
					filemode='w')

#Let us Create an object
logger=logging.getLogger()

#Now we are going to Set the threshold of logger to DEBUG
logger.setLevel(logging.DEBUG)

threads = []
clients = []
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
PROXY_SERV = '127.0.0.1'
PROXY_PORT = 8888
tcpSerSock.bind((PROXY_SERV,PROXY_PORT))
tcpSerSock.listen(5)
print(colored("[INFO] ",'green'),end="")
print(colored('Serving on Port '+str(PROXY_PORT),'white'))
logger.debug("Server running on port "+str(PROXY_PORT))

def proxy(tcpCliSock, addr):
		while True:
			try:
				message =  tcpCliSock.recv(2048)
				if message.decode() == "quit":
					logger.debug("Closing Proxy Server socket")
					tcpSerSock.close()
					for client in clients:
						client.send("exit".encode())
						client.close()
					break

				elif message.decode() != "":
					print(colored("[INFO] ",'green'),end="")
					print(colored("Message from ",'white'),end="")
					print(colored(str(addr[0])+":"+str(addr[1]),'cyan'),end="")
					print(colored(' :- '+message.decode(),'white'))
					filename = message.decode()
					fileExist = "false"
					filepath = "p_www/" + filename
					logger.debug(str(addr[0])+":"+str(addr[1])+" Requesting "+filepath)
					arr = os.listdir("p_www")
					if filename in arr:
						print(colored("[INFO] ",'green'),end="")
						print(colored(filename+" found in Proxy Server. Sending to "+str(addr[0])+':'+str(addr[1]),'white'))
						logger.debug(filename+" found in Proxy Server. Sending to "+str(addr[0])+':'+str(addr[1]))
						f = open(filepath,'r')
						data = f.read()
						tcpCliSock.send(data.encode())
					else:
						print(colored("[INFO] ",'green'),end="")
						print(colored("File not found in Proxy Server. Requesting from Server",'yellow'))
						logger.info(filepath+" not found in Proxy Server. Requesting from Server")
						server = socket(AF_INET, SOCK_STREAM)
						server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
						try:
							server.connect(("127.0.0.1",8081))
							print(colored("[INFO] ",'green'),end="")
							print(colored("Connected to Server. Fetching from server",'white'))
							logger.info("Connected to Server. Fetching "+filename+" from server")
							server.send(filename.encode())
							data = server.recv(2048)
							if data.decode() != 'Nil':
								print(colored("[INFO] ",'green'),end="")
								print(colored(filename+" found in Server. Sending to "+str(addr[0])+':'+str(addr[1]),'white'))
								tcpCliSock.send(data)
							else:
								print(colored("[INFO] ",'green'),end="")
								print(colored(filename+" not found in Server.",'yellow'))
								logger.info(filename+" not found in Server.")
								tcpCliSock.send("File not found".encode())

							server.send("exit".encode())	#disconnect from server
							server.close()
							if "Nil" not in data.decode():
								print(colored("[INFO] ",'green'),end="")
								print(colored("Writing "+filename+"to Proxy Server",'yellow'))
								logger.debug("Writing "+filepath+" to Proxy Server")
								w = open(filepath,'w')
								w.write(data.decode())
								w.close()

						except Exception as e:
							tcpCliSock.send("Unable to fetch file / file not found".encode())
							print(colored("[INFO] ",'green'),end="")
							print(colored("Unable to connect to Server",'yellow'))
							logger.info("Unable to fetch file / file not found")
							logger.error(e)

				else:
					continue

			except Exception as e:
				logger.warning("something went wrong")
				logger.error(e)
				break

while True:
	try:
		tcpCliSock, addr = tcpSerSock.accept()
		clients.append(tcpCliSock)
		print(colored("[INFO] ",'green'),end="")
		print(colored(str(addr[0])+':'+str(addr[1]),'cyan'),end="")
		print(colored(' connected','white'))
		logger.info(str(addr[0])+':'+str(addr[1])+" connected")
		t = threading.Thread(target=proxy, args=(tcpCliSock,addr))
		threads.append(t)
		t.start()
	except:
		logger.warning("Shutting down")
		break

for t in threads:
    t.join()

print(colored("[SHUTDOWN] ",'green'),end="")
print(colored("Proxy Server has shutdown",'white'))
logger.info("Server has shutdown")


import re

#will help us to preprocess the text
def formatting_text(text):
    text = text.split('\n')
    list1 = []
    list1 = text
    list2 = []
    for word in list1:
        res1 = " ".join(re.findall("[a-zA-Z0-9/-]+", word))
        res1 = str(res1)
        if len(res1)>0:
            list2.append(res1.upper())
    return list2


from __init__ import *
from utils import search_utils
from utils import api_utils

# rest api
from kelp_plugins import kelp_plugin_repo

@app.route("/favicon")
@app.route("/favicon.ico")
@app.route("/favicon.png")
def asset_favicon():
    return send_from_directory(f"{app.root_path}/static/", "favicon.png", mimetype="image/vnd.microsoft.icon")

@app.route("/clear-cookies", defaults={"mode": "json"})
@app.route("/clear-cookies/<mode>")
def clear_cookies(mode):
    cookies = request.cookies.items()

    cookie_list = list()
    for cookie in cookies:
        cookie_list.append({"name": cookie[0], "value": cookie[1]})

    if mode == "json":
        data = {"cleared_cookies": cookie_list}
    else:
        data = render_template(
            "cookies-cleared.html",
            cleared_cookies=cookie_list
        )
    response = make_response(data, StopCodes.Success.OK)

    for cookie in cookies:
        response.delete_cookie(cookie[0])

    return response

@app.route("/search_engine")
def search_engine():
    sorted_return = list()

    search = request.args.get("search")

    if search:
        for hit in search_utils.search_all_by_string(search):
            sorted_return.append(hit)

    if "q-search" in request.args:
        return render_template(
            "search_nav.html",
            hits=sorted_return
        )

    return api_utils.craft_response(
        sorted_return, 200
    )

# rest api

@app.route("/api/plugins/tags")
def api_plugin_tags():
    return {"tags": kelp_plugin_repo.get_all_tags()}


from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from .models import Userstore
from django.views.decorators.csrf import csrf_exempt
import json
from django.utils import timezone
from pharmacist.views import getMedicineList
from diagnosticexecutive.views import getDiagnosisList

def deskHome(request):  #Deskexecutive HomePage after login
	return render(request,'deskexecutive/deskHome.html')

def addPatient(request):
	if request.method == "POST":  # checking whether data coming is from post request or not
		# now store all the details from the user in the database
		ssnid = request.POST['ssnid']
		age = request.POST['age']
		name = request.POST['name']
		roomtype = request.POST['roomtype']
		adrs = request.POST['adrs']
		city = request.POST['city']
		state = request.POST['state']
		patientobj = Userstore() #Creating object of the userstore database
		patientobj.ws_ssn = ssnid
		patientobj.ws_pat_name = name
		patientobj.ws_pat_age = age
		patientobj.ws_city = city
		patientobj.ws_state = state
		patientobj.ws_adrs = adrs
		patientobj.ws_status = "Active"
		patientobj.ws_rtype = roomtype
		patientobj.save()
		return redirect('deskexecutive:deskHome') #After adding patient desk executive will be redirected to the Desk executive's Home page
	else:
		return render(request,'deskexecutive/addPatient.html')

def showAllPatient(request):
	user = Userstore.objects  # Getting objects of all the patient in our database
	return render(request,'deskexecutive/showAllPatient.html',{'user':user})

def updatePatient(request):
	if request.method == "POST":
		ws_pat_id=request.POST['uid']
		patientobj = Userstore.objects.get(ws_pat_id=ws_pat_id)

		if request.POST['age']!= patientobj.ws_pat_age:
			patientobj.ws_pat_age = request.POST['age']
		if request.POST['name']!=patientobj.ws_pat_name:
			patientobj.ws_pat_name = request.POST['name']
		if request.POST['roomtype']!=patientobj.ws_rtype:
			patientobj.ws_rtype = request.POST['roomtype']
		if request.POST['adrs']!=patientobj.ws_adrs:
			patientobj.ws_adrs = request.POST['adrs']
		if request.POST['city']!=patientobj.ws_city:
			patientobj.ws_city = request.POST['city']
		if request.POST['state']!=patientobj.ws_state:
			patientobj.ws_state = request.POST['state']
		patientobj.save()
		return redirect('deskexecutive:deskHome')
	else:
		return render(request,'deskexecutive/updatePatient.html')

def deletePatient(request):
	if request.method == "POST":
		ws_pat_id = request.POST['uid']
		patientobj = Userstore.objects.get(ws_pat_id=ws_pat_id)
		# Userstore.objects.filter(ws_pat_id=ws_pat_id).delete()
		patientobj.delete()
		return redirect('deskexecutive:deskHome')
	else:
		return render(request,"deskexecutive/deletePatient.html")

@csrf_exempt
def fetchData(request):
	if request.method == "POST":
		ws_pat_id = request.POST['uid']
		patientobj= get_object_or_404(Userstore,pk=ws_pat_id)

		patientDetails={
		'patientId' : ws_pat_id,
		'patientName': patientobj.ws_pat_name,
		'patientSSN' : patientobj.ws_ssn,
		'patientAge' : patientobj.ws_pat_age,
		'patientCity': patientobj.ws_city,
		'patientState': patientobj.ws_state,
		'patientAdrs' : patientobj.ws_adrs,
		'patientStatus': patientobj.ws_status,
		'patientRtype' : patientobj.ws_rtype,
		'patientDOJ' : str(patientobj.prettyTime)
		}
	return HttpResponse(json.dumps(patientDetails))

@csrf_exempt
def fetchActivePatient(request):
	if request.method == "GET":
		ws_pat_id = request.GET['uid']
		if not (Userstore.objects.filter(ws_pat_id=ws_pat_id).exists()):
			return HttpResponse(json.dumps({'exists':'no'}))
		patientobj= get_object_or_404(Userstore,pk=ws_pat_id)
		patientDetails={
		'exists':'yes',
		'patientId' : ws_pat_id,
		'patientName': patientobj.ws_pat_name,
		'patientSSN' : patientobj.ws_ssn,
		'patientAge' : patientobj.ws_pat_age,
		'patientCity': patientobj.ws_city,
		'patientState': patientobj.ws_state,
		'patientAdrs' : patientobj.ws_adrs,
		'patientStatus': patientobj.ws_status,
		'patientRtype' : patientobj.ws_rtype,
		'patientDOJ' : str(patientobj.prettyTime)
		}
	return HttpResponse(json.dumps(patientDetails))

def billing(request):
	if request.method == "POST":
		pass
	else:
		return render(request,"deskexecutive/billing.html")

@csrf_exempt
def checkout(request):
	if request.method=="GET":
		pid = request.GET['uid']
		patientobj = get_object_or_404(Userstore,ws_pat_id=pid)
		days = str(timezone.now() - patientobj.ws_doj)
		days = int(days[0:days.index(" ")])+1
		if (patientobj.ws_rtype == "General Ward"):
			bedPrice=2000*days
		elif (patientobj.ws_rtype=="Semi-Sharing"):
			bedPrice= days*4000
		else:
			bedPrice=days*8000
		patientDetails={
		'patientId' : patientobj.ws_pat_id,
		'patientName': patientobj.ws_pat_name,
		'patientSSN' : patientobj.ws_ssn,
		'patientRtype' : patientobj.ws_rtype,
		'patientAge' : patientobj.ws_pat_age,
		'patientAdrs' : patientobj.ws_adrs,
		'patientCity': patientobj.ws_city,
		'patientDOJ' : str(patientobj.prettyTime())
		}
		DiagnosTest, testcost= getDiagnosisList(pid)
		medicine, medcost = getMedicineList(pid)
		print(medicine)
		print(DiagnosTest)
		bedDetails={
		'days':days,
		'bedPrice':bedPrice
		}
		data = {"patientDetails":patientDetails,'beds':bedDetails,'medicine':medicine,'DiagnosTest':DiagnosTest}
		return render(request,'deskexecutive/checkout.html',{"total":medcost+testcost+bedPrice,"medcost":medcost,"testcost":testcost,"patientDetails":patientDetails,'days':days,'bedPrice':bedPrice,'medicine':medicine,'DiagnosTest':DiagnosTest})

@csrf_exempt
def searchPatient(request):
	if request.method=="POST":
		ws_pat_id = request.POST['uid']
		if not (Userstore.objects.filter(ws_pat_id=ws_pat_id).exists()):
			return HttpResponse(json.dumps({'exists':'no'}))
		patientobj= get_object_or_404(Userstore,pk=ws_pat_id)
		patientDetails={
		'exists':'yes',
		'patientId' : ws_pat_id,
		'patientName': patientobj.ws_pat_name,
		'patientSSN' : patientobj.ws_ssn,
		'patientAge' : patientobj.ws_pat_age,
		'patientCity': patientobj.ws_city,
		'patientState': patientobj.ws_state,
		'patientAdrs' : patientobj.ws_adrs,
		'patientStatus': patientobj.ws_status,
		'patientRtype' : patientobj.ws_rtype,
		'patientDOJ' : str(patientobj.prettyTime)
		}
		return HttpResponse(json.dumps(patientDetails))
	else:
		return render(request,'deskexecutive/searchPatient.html')


from django.db import models
import datetime
from django.utils import timezone
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    @property
    def is_employee(self):
        if hasattr(self, 'employee'):
            return True
        return False

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    card_id=models.BigIntegerField()
    name=models.CharField(max_length=60, blank=True, null=True)
    phone=models.BigIntegerField(blank=True, null=True)
    department=models.CharField(max_length=60, blank=True, null=True)
    email=models.EmailField(blank=True, null=True)
    address=models.CharField(max_length=100, blank=True, null=True)
    def __str__(self):
        '''if self.name==None:
            return str(self.card_id)
        else:
            return str(self.name) + ' : ' + str(self.card_id)'''
        return str(self.name)

class Record(models.Model):
    emp = models.ManyToManyField(Employee)
    ids=models.IntegerField(default=0)
    card_id=models.BigIntegerField()
    name=models.CharField(max_length=60, blank=True, null=True)
    department=models.CharField(max_length=60, blank=True, null=True)
    date=models.DateField(default=datetime.date.today)
    time_in=models.TimeField(default=datetime.datetime.now())
    time_out=models.TimeField(blank=True, null=True)
    status=models.TextField(max_length=100)

    def __str__(self):
        return str(self.name) + ' : ' + str(self.date)

class EmpLeaveRequests(models.Model):
    remp = models.ForeignKey(Employee, on_delete=models.CASCADE)
    content = models.CharField(max_length=100)
    date_from = models.DateField(max_length= 100, default=None)
    date_to = models.DateField(max_length=100, default=None)
    status = models.CharField(max_length=100, null=True)

class AppStatus(models.Model):
    leaveApp = models.ForeignKey(EmpLeaveRequests, on_delete=models.CASCADE)
    status = models.CharField(max_length=100, null=True)

class Notification(models.Model):
    content = models.CharField(max_length=1000, null=True)
    date=models.DateField(default=datetime.date.today)

class Tickets(models.Model):
    temp = models.ForeignKey(Employee, on_delete=models.CASCADE)
    content = models.CharField(max_length=100)
    date = models.DateField(max_length= 100, default=None)
    status = models.CharField(max_length=100, null=True)


from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
__all__ = ['PyReplyEncoder']

import pickle

import CPL
from Hub.Reply.FullReply import FullReply
from .ReplyEncoder import ReplyEncoder

class PyReplyEncoder(ReplyEncoder):
    """ Encode Replys as single-line pickled python objects.
    """

    def __init__(self, **argv):
        ReplyEncoder.__init__(self, **argv)

        # How do we terminate encoded lines?
        #
        self.EOL = argv.get('EOL', '\f')
        self.encode = self.encodeFull

    def encodeFull(self, r, nub, noKeys=False):
        """ Encode a reply for a given nub.

        Encode all the information required to track the source of the command and the reply.
        """

        fullReply = FullReply()
        fullReply.initFromReply(r, noKeys)
        fullPickle = pickle.dumps(fullReply)

        if self.debug > 6:
            CPL.log('PyEncode.encode', 'encoding FullReply %s as %r' % (fullReply, fullPickle))
        elif self.debug > 3:
            CPL.log('PyEncode.encode', 'encoding FullReply %s' % (fullReply,))

        return "%s%s" % (fullPickle, self.EOL)


# import os
#
# from celery import Celery
#
# # set the default Django settings module for the 'celery' program.
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
#
# app = Celery('proj')
#
# # Using a string here means the worker doesn't have to serialize
# # the configuration object to child processes.
# # - namespace='CELERY' means all celery-related configuration keys
# #   should have a `CELERY_` prefix.
# app.config_from_object('django.conf:settings', namespace='CELERY')
#
# # Load task modules from all registered Django app configs.
# app.autodiscover_tasks()    # 发现所有tasks.py
#
#
# @app.task(bind=True)
# def debug_task(self):
#     print(f'Request: {self.request!r}')

# -*-coding=utf-8-*-

from __future__ import absolute_import

from celery import Celery

from kombu import Queue

app = Celery("cele",
             broker="redis://192.168.56.102:6379/1",
             include=['hotplay_task']
             )

app.conf.update(
    CELERY_DEFAULT_QUEUE='hotplay_sh_default_queue',
    # CELERY_QUEUES = (Queue('hotplay_jy_queue'),),  #该队列是给server2用的，并不需要在这里申明

)


# -*- coding: utf-8 -*-
#
#       ramstk.modules.function.Controller.py is part of The RAMSTK
#       Project
#
# All rights reserved.
# Copyright 2007 - 2017 Doyle Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Function Package Data Controller."""

# Import third party modules.
from pubsub import pub

# Import other RAMSTK modules.
from ramstk.modules import RAMSTKDataController
from ramstk.modules import RAMSTKDataMatrix
from ramstk.dao import RAMSTKFunction, RAMSTKHardware, RAMSTKSoftware
from . import dtmFunction

class FunctionDataController(RAMSTKDataController):
    """
    Provide interface between Function data model and RAMSTK view model.

    A single Function controller can manage one or more Function data
    models.  The attributes of a Function data controller are:
    """

    def __init__(self, dao, configuration, **kwargs):
        """
        Initialize a Function data controller instance.

        :param dao: the RAMSTK Program DAO instance to pass to the
                    Function Data Model.
        :type dao: :class:`ramstk.dao.DAO`
        :param configuration: the Configuration instance associated with
                              the current instance of the RAMSTK
                              application.
        :type configuration: :class:`ramstk.Configuration.Configuration`
        """
        RAMSTKDataController.__init__(
            self,
            configuration,
            model=dtmFunction(dao, **kwargs),
            ramstk_module='function',
            **kwargs)

        # Initialize private dictionary attributes.

        # Initialize private list attributes.

        # Initialize private scalar attributes.
        self._dmx_fctn_hw_matrix = RAMSTKDataMatrix(dao, RAMSTKFunction,
                                                    RAMSTKHardware)
        self._dmx_fctn_sw_matrix = RAMSTKDataMatrix(dao, RAMSTKFunction,
                                                    RAMSTKSoftware)

        # Initialize public dictionary attributes.

        # Initialize public list attributes.

        # Initialize public scalar attributes.

        # Subscribe to PyPubSub messages.
        pub.subscribe(self.request_do_select_all, 'selected_revision')
        pub.subscribe(self.request_do_delete, 'request_delete_function')
        pub.subscribe(self.request_do_insert, 'request_insert_function')
        pub.subscribe(self.request_do_update, 'request_update_function')
        pub.subscribe(self.request_do_update_all,
                      'request_update_all_functions')
        pub.subscribe(self.request_set_attributes, 'editing_function')

    def request_do_create(self, revision_id, matrix_type):
        """
        Request to create or refresh a Function matrix.

        :param int revision_id: the ID of the Revision the desired Matrix is
                                associated with.
        :param str matrix_type: the type of the Matrix to select all rows and
        """
        if matrix_type == 'fnctn_hrdwr':
            self._dmx_fctn_hw_matrix.do_create(
                revision_id,
                matrix_type,
                rkey='function_id',
                ckey='hardware_id')

        return

    def request_do_select_all(self, revision_id):
        """
        Retrieve the treelib Tree() from the Function Data Model.

        :return: tree; the treelib Tree() of RAMSTKFunction models in the
                 Function tree.
        :rtype: :class:`treelib.Tree`
        """
        return self._dtm_data_model.do_select_all(revision_id=revision_id)

    def request_do_select_all_matrix(self, revision_id, matrix_type):
        """
        Retrieve all the Matrices associated with the Function.

        :param int revision_id: the Revision ID to select the matrices for.
        :param int matrix_type: the type of the Matrix to retrieve.  Current
                                Function matrix types are:

                                fnctn_hrdwr = Function:Hardware
                                fnctn_sftwr = Function:Software
                                fnctn_vldtn = Function:Validation

        :return: (_matrix, _column_hdrs, _row_hdrs); the Pandas Dataframe,
                 noun names to use for column headings, noun names to use for
                 row headings.
        :rtype: (:class:`pandas.DataFrame`, dict, dict)
        """
        _matrix = None
        _column_hdrs = []
        _row_hdrs = []

        if matrix_type == 'fnctn_hrdwr':
            self._dmx_fctn_hw_matrix.do_select_all(
                revision_id,
                matrix_type,
                rkey='function_id',
                ckey='hardware_id',
                rheader='function_code',
                cheader='comp_ref_des')
            _matrix = self._dmx_fctn_hw_matrix.dtf_matrix
            _column_hdrs = self._dmx_fctn_hw_matrix.dic_column_hdrs
            _row_hdrs = self._dmx_fctn_hw_matrix.dic_row_hdrs

        return (_matrix, _column_hdrs, _row_hdrs)

    def request_do_insert(self, revision_id, parent_id, **kwargs):  # pylint: disable=unused-argument
        """
        Request to add an RAMSTKFunction table record.

        :return: False if successful or True if an error is encountered.
        :rtype: bool
        """
        _error_code, _msg = self._dtm_data_model.do_insert(
            revision_id=revision_id, parent_id=parent_id)

        return RAMSTKDataController.do_handle_results(self, _error_code, _msg,
                                                      None)

    def request_do_insert_matrix(self, matrix_type, item_id, heading,
                                 row=True):
        """
        Request the to add a new row or column to the Data Matrix.

        :param str matrix_type: the type of the Matrix to retrieve.  Current
                                Function matrix types are:

                                fnctn_hrdwr = Function:Hardware
                                fnctn_sftwr = Function:Software
                                fnctn_vldtn = Function:Validation

        :param int item_id: the ID of the row or column item to insert into the
                            Matrix.
        :param str heading: the heading for the new row or column.
        :keyword bool row: indicates whether to insert a row (default) or a
                           column.
        :return: False if successful or True if an error is encountered.
        :rtype: bool
        """
        if matrix_type == 'fnctn_hrdwr':
            _error_code, _msg = self._dmx_fctn_hw_matrix.do_insert(
                item_id, heading, row=row)

        if _error_code == 0 and not self._test:
            pub.sendMessage(
                'insertedMatrix',
                matrix_type=matrix_type,
                item_id=item_id,
                row=row)

        return RAMSTKDataController.do_handle_results(self, _error_code, _msg,
                                                      None)

    def request_do_delete(self, node_id):
        """
        Request to delete an RAMSTKFunction table record.

        :param int node_id: the PyPubSub Tree() ID of the Function to delete.
        :return: False if successful or True if an error is encountered.
        :rtype: bool
        """
        _error_code, _msg = self._dtm_data_model.do_delete(node_id)

        return RAMSTKDataController.do_handle_results(self, _error_code, _msg,
                                                      None)

    def request_do_delete_matrix(self, matrix_type, item_id, row=True):
        """
        Request to remove a row or column from the selected Data Matrix.

        :param str matrix_type: the type of the Matrix to retrieve.  Current
                                Function matrix types are:

                                fnctn_hrdwr = Function:Hardware
                                fnctn_sftwr = Function:Software
                                fnctn_vldtn = Function:Validation

        :param int item_id: the ID of the row or column item to remove from the
                            Matrix.
        :keyword bool row: indicates whether to insert a row (default) or a
                           column.
        :return: False if successful or True if an error is encountered.
        :rtype: bool
        """
        if matrix_type == 'fnctn_hrdwr':
            _error_code, _msg = self._dmx_fctn_hw_matrix.do_delete(
                item_id, row=row)

        return RAMSTKDataController.do_handle_results(self, _error_code, _msg,
                                                      'deletedMatrix')

    def request_do_update(self, node_id):
        """
        Request to update an RAMSTKFunction table record.

        :param int node_id: the PyPubSub Tree() ID of the Function to save.
        :return: False if successful or True if an error is encountered.
        :rtype: bool
        """
        _error_code, _msg = self._dtm_data_model.do_update(node_id)

        return RAMSTKDataController.do_handle_results(self, _error_code, _msg,
                                                      None)

    def request_do_update_matrix(self, revision_id, matrix_type):
        """
        Request to update the selected Data Matrix.

        :param int revision_id: the ID of the Revision is the matrix to update
                                is associated with.
        :param int matrix_type: the type of the Matrix to save.
        :return: False if successful or True if an error is encountered.
        :rtype: bool
        """
        if matrix_type == 'fnctn_hrdwr':
            _error_code, _msg = self._dmx_fctn_hw_matrix.do_update(
                revision_id, matrix_type)
        else:
            _error_code = 6
            _msg = 'RAMSTK ERROR: Attempted to update non-existent matrix ' \
                   '{0:s}.'.format(matrix_type)

        return RAMSTKDataController.do_handle_results(self, _error_code, _msg,
                                                      'savedMatrix')

    def request_do_update_all(self, **kwargs):  # pylint: disable=unused-argument
        """
        Request to update all records in the RAMSTKFunction table.

        :return: (_error_code, _msg); the error code and associated message.
        :rtype: (int, str)
        """
        _error_code, _msg = self._dtm_data_model.do_update_all()

        return RAMSTKDataController.do_handle_results(self, _error_code, _msg,
                                                      None)

    def request_set_attributes(self, module_id, key, value):
        """
        Request to set a Function attribute.

        :param int module_id: the ID of the entity who's attribute is to
                              be set.
        :param str key: the key of the attributes to set.
        :param value: the value to set the attribute identified by the
                      key.
        :return:
        :rtype:
        """
        _entity = self.request_do_select(module_id)
        _attributes = _entity.get_attributes()

        _attributes[key] = value

        return _entity.set_attributes(_attributes)


import os
import sys
import time
import random
import serial
from YModem import YModem

def main(argv):
    serial_io = serial.Serial()
    try:
        filename = argv[0]
        serial_io.port = argv[1]
        serial_io.baudrate = argv[2]
    except Exception as e:
        print ('python ymodem_sender.py <filename> <device> <baudrate>')
    serial_io.parity = "N"
    serial_io.bytesize = 8
    serial_io.stopbits = 1
    serial_io.timeout = 2
    try:
        serial_io.open()
    except Exception as e:
        raise Exception("Failed to open serial port!")

    def sender_getc(size):
        return serial_io.read(size) or None

    def sender_putc(data, timeout=15):
        return serial_io.write(data)

    os.chdir(sys.path[0])
    file_path = os.path.abspath(filename)
    sender = YModem(sender_getc, sender_putc)
    sent = sender.send_file(file_path)
    serial_io.close()

if __name__ == '__main__':
    main(sys.argv[1:])


#!/bin/env python
import requests
import re
from months import months
from datetime import datetime
import json

class CheckLatestCODUpdate:
    def __init__(self):
        self.url = None
        self.loc = "./resources"
        self.current_patch_date = None
        self.previous_date = None
        self.first_date = None
        self.second_date = None
        self.url = None

    def query_google(self):
        print("Querying Google")
        self.output_message_to_logfile(f"{datetime.today()}: Querying Google")
        res = requests.get("https://www.google.com/search?&q=call+of+duty+patch+notes")
        #self.output_message_to_logfile(f"{datetime.today()}: Google Response:\n{res.content.decode('ISO-8859-1')}")
        return res.content.decode("ISO-8859-1")

    def search_for_cod_patch_notes(self, res):
        print("Searching for COD Patch Notes")
        self.output_message_to_logfile(f"{datetime.today()}: Searching for COD Patch Notes")
        pattern = '(https:\/\/www\.infinityward\.com\/news\/[0-9][0-9][0-9][0-9]-[0-9][0-9]\/.*_PATCH_NOTES_..._...)'
        x = re.search(pattern, res)
        self.output_message_to_logfile(f"{datetime.today()}: Found: {x.group(0)}")
        self.url = x.group(0);
        return x.group(0)

    def get_first_part_of_date(self, response):
        print(f"Check date of patch notes in rgex line: {response}")
        self.output_message_to_logfile(f"{datetime.today()}: Check date of patch notes in rgex line: {response}")
        first_part_of_date = re.search("[0-9][0-9][0-9][0-9]-[0-9][0-9]", response).group(0)
        print(first_part_of_date)
        self.output_message_to_logfile(f"{datetime.today()}: Found: {first_part_of_date}")
        return first_part_of_date

    def get_second_part_of_date(self, response):
        print(f"Check date of patch notes in regex line: {response}")
        self.output_message_to_logfile(f"{datetime.today()}: Getting second part of date")
        for month in months:
            if month in response.lower():
                print(f"Month found: {month}")
                self.output_message_to_logfile(f"{datetime.today()}: Month found {month}")
                pattern = f'({month.upper()}_[0-9].)'
                second_part_of_date = re.search(pattern, response).group(0)

                if second_part_of_date[-1].isdigit():
                    second_part_of_date = second_part_of_date
                else:
                    second_part_of_date = second_part_of_date[:-1]
                print(second_part_of_date)
                self.output_message_to_logfile(f"{datetime.today()}: Second part of date: {second_part_of_date}")
                return second_part_of_date
        print("Month not found")
        self.output_message_to_logfile(f"{datetime.today()}: Month not found")
        return ""

    def format_date(self, first_date, second_date):
        print("Formatting Dates")
        self.output_message_to_logfile(f"{datetime.today()}: Formatting Dates")
        second_date = second_date.split("_")[1]
        formatted_date = f"{first_date}-{second_date}"
        return formatted_date

    def save_date_of_most_recent_patch_notes(self, date):
        print(f"Saving most recent patch date to file: {date}")
        self.output_message_to_logfile(f"{datetime.today()}: Saving most recent patch date to file: {date}")
        f = open(f"{self.loc}resources/patch-date.txt", "w")
        f.write(date)
        f.close()

    def read_date_of_last_patch(self):
        self.output_message_to_logfile(f"{datetime.today()}: Reading last date from file..")
        f = open(f"{self.loc}resources/patch-date.txt", "r")
        self.previous_patch_date = f.read()
        self.output_message_to_logfile(f"{datetime.today()}: Last date from file: {self.previous_patch_date}")
        return self.previous_patch_date

    def new_patch_is_released(self, current_date):
        print(f"Current Date: {current_date}\nPrevious Date: {self.previous_patch_date}")
        self.output_message_to_logfile(
            f"{datetime.today()}: Current Date: {current_date}\nPrevious Date: {self.previous_patch_date}"
        )
        current_date_converted = datetime.strptime(current_date, "%Y-%m-%d")
        previous_update_date_converted = datetime.strptime(self.previous_patch_date, "%Y-%m-%d")
        self.output_message_to_logfile(f"{datetime.today()}: Current Date Converted: {current_date_converted}\n{datetime.today()}: Previous Date Converted: {previous_update_date_converted}")
        print(f"Current Date Converted: {current_date_converted}\nPrevious Date Converted: {previous_update_date_converted}")
        if current_date_converted > previous_update_date_converted:
            print("Update now available!")
            self.output_message_to_logfile(f"{datetime.today()}: Update Available!")
            self.save_date_of_most_recent_patch_notes(current_date)
            return True
        else:
            print("No update available")
            self.output_message_to_logfile(f"{datetime.today()}: No update available")
            return False

    def generate_patch_notes_url(self, first_date, second_date):
        print("Generating URL...")
        self.output_message_to_logfile(f"{datetime.today()}: Generating URL")
        global url
        url = self.url
        print(f"Generated: {url}")
        self.output_message_to_logfile(f"{datetime.today()}: Generated: {url}")
        return url

    def verify_if_correct_url_is_generated(self, url):
        res = requests.get(url)
        res = res.content.decode("utf8")
        if "Sorry, an unexpected error occurred" in res:
            print("Incorrect URL Generated")
            self.output_message_to_logfile(f"{datetime.today()}: Incorrect URL generated")
            return None
        else:
            print("URL is valid")
            self.output_message_to_logfile(f"{datetime.today()}: URL is valid")
            return True

    def check_if_new_patch_is_released(self, current_patch_date):
        if self.new_patch_is_released(current_patch_date):
            self.patch_url = self.generate_patch_notes_url(self.first_part_of_date, self.second_part_of_date)
            verify_url = self.verify_if_correct_url_is_generated(url)
            return verify_url

    def send_slack_message(self, message, hook):
        print("Sending Slack message...")
        self.output_message_to_logfile(f"{datetime.today()}: Sending Slack message...")
        slack_hook = f"https://hooks.slack.com/services/{hook}"
        payload = {"text": message}
        json_payload = json.dumps(payload)
        res = requests.post(slack_hook, data=json_payload)
        print(res.status_code)
        self.output_message_to_logfile(f"{datetime.today()}: {res.status_code}")

    def output_messages_to_logfile(self, messages):
        f = open(f"{self.loc}resources/log.txt", "a")
        for message in messages:
            f.write(f"{message}\n")
        f.close()

    def output_message_to_logfile(self, message):
        self.loc = "./"
        f = open(f"{self.loc}resources/log.txt", "a")
        f.write(f"{message}\n")
        f.close()

    @property
    def location(self):
        return self.loc

    @location.setter
    def location(self, loc):
        self.loc = loc

    @property
    def patch_url(self):
        return self.url

    @patch_url.setter
    def patch_url(self, url):
        self.url = url

    @property
    def previous_patch_date(self):
        return self.previous_date

    @previous_patch_date.setter
    def previous_patch_date(self, previous_date):
        self.previous_date = previous_date

    @property
    def first_part_of_date(self):
        return self.first_date

    @first_part_of_date.setter
    def first_part_of_date(self, first_date):
        self.first_date = first_date

    @property
    def second_part_of_date(self):
        return self.second_date

    @second_part_of_date.setter
    def second_part_of_date(self, second_date):
        self.second_date = second_date


#!/usr/bin/python

#################################################################################
#   Public - Private Key Encryption                                             #
#   Author: Jacob A. Lindow                                                     #
#                                                                               #
#   SY301 - Project 3                                                           #
#                                                                               #
#################################################################################
#################################################################################
# Usage: $ python3 enc.py public.dot msg.txt                                    #
#                                                                               #
# Functionality:                                                                #
#   1) Read msg.txt and convert to an integer                                   #
#   2) Create a new graph with nodes public.dot                                 #
#       - While creating graph, assign random number values to each node        #
#   3) Make the last node some int such that the sum equals the msg integer     #
#   4) Iterate through the graph and assign a second num to each node           #
#      equal to the sum of all neighbors first num                              #
#   5) Create a cipherText with every nodeName and corresponding second int     #
#       e.g      nodeName + " " + INT + "\n" + nodeName etc...                  #
#   6) Output cipherText                                                        #
#################################################################################
import sys
import random
#################################################################################
class Node:
    def __init__ (self, name):
        self.name           = name
        self.value          = random.randint(1, 100)
        self.neighborSum    = 0
        self.neighbors      = set()

    def addNeighbor(self, neighbor):
        self.neighbors.add(neighbor)

    def __str__ (self):
        return str(self.name)

class Graph:
    def __init__ (self, fname):
        """ Read in dot file and create a graph """
        with open(fname) as dotin:
            wholefile = dotin.read()

        openbrace   = wholefile.index('{')
        closebrace  = wholefile.index('}')

        gtype, self._gname = wholefile[:openbrace].split()
        edgesep = '--'

        self.vmap = {}

        for edgestr in wholefile[openbrace+1:closebrace].split(';'):
            left, sep, right = edgestr.partition(edgesep)
            if sep == "":
                continue

            a = left.strip()
            b = right.strip()

            if a not in self.vmap:
                self.vmap[a] = Node(a)
            if b not in self.vmap:
                self.vmap[b] = Node(b)

            self.vmap[a].addNeighbor(self.vmap[b])
            self.vmap[b].addNeighbor(self.vmap[a])

    def isAdjacent(self, vertexA, vertexB):
        return self.vmap[vertexB] in self.vmap[vertexA].neighbors

    def neighbors(self, vertexA):
        return list(self.vmap[vertexA].neighbors)

    def vertices(self):
        return list(self.vmap)

    def encode(self, msg):
        msg = int.from_bytes(str.encode(msg, 'ascii'), byteorder = 'big')
        print("Message: " + str(msg))

        #Make the sum of all nodes equal msg
        graphSum = 0
        for key in self.vmap:
            graphSum += self.vmap[key].value

            name = self.vmap[key].name

        self.vmap[name].value += (msg - graphSum)

        print("Graph Sum: " + str(graphSum))

        for key in self.vmap:
            print("KEY: " + self.vmap[key].name + ", VALUE: " + str(self.vmap[key].value))

        #Make the second int for each node the sum of all neighbors
        for key in self.vmap:
            secondInt = 0;

            neighborList   = self.neighbors(self.vmap[key].name)

            for i in range(len(neighborList)):
                secondInt += neighborList[i].value

            secondInt += self.vmap[key].value
            self.vmap[key].neighborSum = secondInt

        #Create ciphertext
        ciphertext = ""
        for key in self.vmap:
            ciphertext += str(self.vmap[key].name) + " " + str(self.vmap[key].neighborSum) + "\n"
        return ciphertext

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

#Read msg.txt and convert to an integer
with open(sys.argv[2]) as msgFile:
    msg = msgFile.read()

#Create a graph with nodes from public key
publicKey   = Graph(sys.argv[1])
ciphertext  = publicKey.encode(msg)
print(ciphertext)


from sys import stdin
def solve(a):
    suma2=0
    for x in range(len(a)):
        suma=0
        for elm in range(x):
            suma= suma+ a[elm][0]
        suma2+= (suma+ (a[x][0]- a[x][1]))
    print(int(suma2/len(a)))
def main():
    casos,n= int(stdin.readline().strip()),[]
    for elm in range(casos):
        N= [int(i) for i in stdin.readline().strip().split()]
        n.append(N[::-1])
    n.sort()
    solve(n)
main()


"""
@Time:2018/1/30 9:44
@Author:xuzhongyou
"""
#大意为：平面上有若干个点，我们需要用一些线段将这些点连接起来使任意两个点通过一系列的线段相联
#求一种连接方式使所有线段的长度和最小，求该长度和
#注意，题目给的是点的坐标，当然需要转化为图上的结点。边，有权值
#注意一个套路，最小生成树的问题，最好用类来解决。

#其实并不需要纠结坐标的问题，这是有点变扭
class edge:
    def __init__(self,a,b,cost):
        self.a = a
        self.b = b
        self.cost = cost

class node:
    def __init__(self,x,y):
        self.x = x
        self.y = y

def cal_cost(node1,node2):
    return ((node1.x-node2.x)**2+(node1.y-node2.y)**2)**(0.5)

node_list = list()
edj_list = []
n = int(input())
#node_list从零开始
for i in range(n):
    inputs = input().split(" ")
    num1 = float(inputs[0])
    num2 = float(inputs[1])
    node_list.append(node(num1,num2))
#计算权重n(n-1)/2次
for i in range(n):
    for j in range(i+1,n):
        cost = cal_cost(node_list[i],node_list[j])
        edj_list.append(edge(i,j,cost))
#并查集
def findroot(x):
    if flag[x] == -1:return x
    else:
        temp = findroot(flag[x])
        flag[x] = temp
        return temp

#sorted完之后要赋值
edj_list = sorted(edj_list,key=lambda edj:edj.cost)
m = 100
#flag并不影响结果
flag = [-1]*m
ans = 0
for edj in edj_list:
    a = findroot(edj.a)
    b = findroot(edj.b)
    if a!=b :
        flag[a] = b
        ans += edj.cost
print('%.2f'%ans)


import csv
import pandas as pd
import numpy as np
import os
import os.path
from os import path
from cor import WebScraper
import threading

__states=None
__districts=None

def load_states():
    global __states
    print('calling read_samplce_csv')
    df=read_sample_csv()
    print('got response from read_samplce_csv')
    __states=df['state'].unique()
    __states = __states.tolist()

def load_district(state):
    global __districts
    df=read_sample_csv()
    inpst=df.loc[df['state']==state]
    __districts=inpst.district.unique().tolist()
    return __districts

def get_states():
    return __states

def add_and_get_email(district,email):
    df=read_sample_csv()
    inpds=df.loc[df['district']==district]
    inpds['email']=email
    inpds.to_csv(r'userID.csv',mode='a',header=False,index=False,quoting=csv.QUOTE_NONNUMERIC)
    print('added email :', email)
    return inpds.values.tolist()

def read_sample_csv():
    if not path.exists('sample.csv'):
        t = WebScraper(callback=load_states)
        t.start()
        return pd.DataFrame(data= [[None for _ in range(6)]], columns=('state','district','case','cured','active','death'))
    else:
        return pd.read_csv("sample.csv")
if __name__=='__main__':
    load_states()
    load_district()
    print(__states)
    print(__districts)


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='gallery-index'),
    path('videos/', views.videos, name='videos'),
    path('backstage/', views.backstage, name='backstage'),
    path('stories/', views.stories, name='stories'),
    path('large_format/', views.large_format, name='large_format'),
    path('multimedia/', views.multimedia, name='multimedia'),
]


from sklearn.base import BaseEstimator
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz

import xgboost as xgb
import numpy as np

class ClassifierRandomForest(BaseEstimator):
    def __init__(self):
        print("I don't like classifying people :(")

    def fit(self, X, y):
        self.clf = RandomForestClassifier(
            n_estimators=2, max_leaf_nodes=2, random_state=61)
        self.clf.fit(X, y)

    def predict(self, X):
        return self.clf.predict(X)

    def predict_proba(self, X):
        return self.clf.predict_proba(X)

# ----------------------------------------------------------------------

class ClassifierSimpleTree(BaseEstimator):
    def __init__(self, nleaf=80):
        self.clf = DecisionTreeClassifier(
            max_depth=80,
            max_features=57,
            max_leaf_nodes=nleaf
        )
        self.nleaf = nleaf
        self.feats = nleaf
        self.name = 'ClassifierSimpleTree' + '_nleaf' + str(self.nleaf)
        print(self.name)

    def fit(self, X, y):
        self.clf.fit(X, y)
        with open("simple_tree.dot", 'w') as f:
            f = export_graphviz(self.clf, out_file=f)

        importances = self.clf.feature_importances_
        indices = np.argsort(importances)[::-1]

        # Print the feature ranking
        print("Feature ranking:")
        for f in range(X.shape[1]):
            print("%d. feature %d (%f)" %
                  (f, indices[f], importances[indices[f]]))

    def predict(self, X):
        return self.clf.predict(X)

    def predict_proba(self, X):
        return self.clf.predict_proba(X)

class ClassifierXGB(BaseEstimator):
    def __init__(self, level=0):
        self.name = 'ClassifierXGB' + '_feat' + str(level)
        print(self.name)
        pass

    def fit(self, X, y):
        dtrain = xgb.DMatrix(X, y)
        param = {'objective': 'binary:logistic', 'max_depth': 8,
                 'subsample': 1, 'eta': 0.1, 'num_round': 400,
                 'gamma': 0, 'silent': 1}
        self.clf = xgb.train(param, dtrain,
                             num_boost_round=param['num_round'])
        print("weight scores")
        print(self.clf.get_score(importance_type="weight"))
        print("gain scores")
        print(self.clf.get_score(importance_type="gain"))
        print("cover scores")
        print(self.clf.get_score(importance_type="cover"))

    def predict(self, X):
        dpred = xgb.DMatrix(X)
        return (np.sign(self.clf.predict(dpred) - 0.5) / 2 + 0.5)

    def predict_proba(self, X):
        dpred = xgb.DMatrix(X)
        pred = self.clf.predict(dpred)
        pred = np.array([1 - pred, pred]).T
        return pred

Classifier = ClassifierRandomForest
#Classifier = ClassifierSimpleTree
#Classifier = ClassifierXGB

# class Classifier(ClassifierSimpleTree):
#    def __init__(self):
#        ClassifierSimpleTree.__init__(self)
#        pass