#evaluation of postfix expression
class Evaluate:
    def __init__(self):
        self.stack = []

    def isDigit(self, digit):
        if ord(digit) >= 48 and ord(digit) <= 57:
            return 1
        else:
            return 0

    def evaluatepostfix(self, exp):
        for i in range(len(exp)):
            if self.isDigit(exp[i]):
                self.stack.append(int(exp[i]))
            elif exp[i] == " ":
                pass
            else:
                op2 = self.stack.pop()
                op1 = self.stack.pop()
                op = self.perform(exp[i], op1, op2)
                self.stack.append(op)

        return self.stack.pop()

    def perform(self, operator, op1, op2):
        if operator == '+':
            return op1 + op2
        elif operator == '-':
            return op1 - op2
        elif operator == '*':
            return op1 * op2
        elif operator == '/':
            return op1 / op2
        else:
            return '!'

if __name__ == "__main__":

    exp = input("Enter postfix expression to evaluate : ")
    ev = Evaluate()
    print(ev.evaluatepostfix(exp))


from django.urls import path
from appcoder import views
from django.contrib.auth.views import LogoutView

urlpatterns = [
    path("", views.inicio, name="coder-inicio"),

    path("estudiantes/", views.estudiantes, name="coder-estudiantes"),

    path("profesores/", views.profesores, name="coder-profesores"),

    path("profesores/crear/", views.creacion_profesores, name="coder-profesores-crear"),

    path("cursos/", views.cursos,name="coder-cursos"),

    path("cursos/crear/", views.creacion_curso, name="coder-cursos-crear"),

    path("cursos/buscar/", views.busqueda_curso, name="coder-cursos-buscar"),

    path("cursos/borrar/<id>/", views.eliminar_curso, name="coder-cursos-borrar"),

    path("cursos/editar/<id>", views.editar_curso, name="coder-cursos-editar"),

    path("cursos/buscar/resultados", views.resultado_busqueda_cursos, name="coder-cursos-resultado-busqueda"),

    path("entregables/", views.entregables, name="coder-entregables"),

    path("login/", views.iniciar_sesion, name="auth-login"),

    path("register/", views.registrar_usuario, name ="reg-user"),

    path("logout/", LogoutView.as_view(template_name='appcoder/logout.html'), name = "auth-logout"),

    path("perfil/editar/", views.editar_perfil, name="auth-editar-perfil"),

    path("perfil/avatar/", views.agregar_avatar, name="auth-avatar"),
]


import sys, os
sys.path.append(os.path.abspath(".."))

import uvicorn as uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.database import engine
from app import models

# For DEV only, remove below 4 lines in production
from app.dependency import create_default_data
models.Base.metadata.drop_all(bind=engine)
models.Base.metadata.create_all(bind=engine)
create_default_data()

app = FastAPI()

origins = ["*"]
origins = [
    "http://localhost",
    "http://localhost:8080",
    "http://192.168.0.123:8080"
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['GET','POST'],
    allow_headers=["*"],
)

from app.api import user, task, workhour
app.include_router(user.router)
app.include_router(task.router)
app.include_router(workhour.router)

@app.get("/")
async def root():
    return "Hello FastAPI"

if __name__ == '__main__':
	uvicorn.run("main:app", host='0.0.0.0', port=8000)


from bs4 import BeautifulSoup
import chardet
import requests
import pprint
import json
import pandas as pd
import numpy as np

'''
creat beautifulsoup
'''
def creat_bs(url):
    result = requests.get(url)
    e=chardet.detect(result.content)['encoding']
    #set the code of request object to the webpage's code
    result.encoding=e
    c = result.content
    soup=BeautifulSoup(c,'lxml')
    return soup
'''
build urls group
'''
def build_urls(prefix,suffix):
    urls=[]
    for item in suffix:
        url=prefix+item
        urls.append(url)
    return urls
'''
acquire all the page titles and links and save it
'''
def find_title_link(soup):
    titles=[]
    links=[]
    try:
        contanier=soup.find('div',{'class':'container_padd'})
        ajaxtable=contanier.find('form',{'id':'ajaxtable'})
        page_list=ajaxtable.find_all('li')
        for page in page_list:
            titlelink=page.find('a',{'class':'truetit'})
            if titlelink.text==None:
                title=titlelink.find('b').text
            else:
                title=titlelink.text
            if np.random.uniform(0,1)>0.90:
                link=titlelink.get('href')
                titles.append(title)
                links.append(link)
    except:
        print('have none value')
    return titles,links

'''
acquire reply in every topic of 10 page
'''
def find_reply(soup):
    replys=[]
    try:
        details=soup.find('div',{'class':'hp-wrap details'})
        form=details.find('form')
        floors=form.find_all('div',{'class':'floor'})
        for floor in floors:
            table=floor.find('table',{'class':'case'})
            if floor.id!='tpc':
                if table.find('p')!=None:
                    reply=table.find('p').text
                else:
                    reply=table.find('td').text
                replys.append(reply)
            elif floor.id=='tpc':
                continue
    except:
        return None
    return replys

'''
acquire information from hupu pubg bbs
'''
url='https://bbs.hupu.com/pubg'
page_suffix=['','-2','-3','-4','-5','-6','-7','-8','-9','-10','-11','-12',
'-13','-14','-15','-16','-17','-18','-19','-20','-21','-22','-23','-24',
'-25','-26','-27','-28','-29','-30']
urls=build_urls(url,page_suffix)

title_group=[]
link_group=[]
for url in urls:
    soup=creat_bs(url)
    titles,links=find_title_link(soup)
    for title in titles:
        title_group.append(title)
    for link in links:
        link_group.append(link)

reply_urls=build_urls('https://bbs.hupu.com',link_group)
reply_group=[]
for url in reply_urls:
    soup=creat_bs(url)
    replys=find_reply(soup)
    if replys!=None:
        for reply in replys:
            reply_group.append(reply)

'''
creat wordlist and save as txt
'''
wordlist=str()
for title in title_group:
    wordlist+=title

for reply in reply_group:
    wordlist+=reply

def savetxt(wordlist):
    f=open('wordlist.txt','wb')
    f.write(wordlist.encode('utf8'))
    f.close()
savetxt(wordlist)


# Puzle lineal con busqueda en profundidad recursiva
from arbol import Nodo

def buscar_solucion(nodo_inicial, solucion, visitados):
    visitados.append(nodo_inicial.get_datos())

    if nodo_inicial.get_datos() == solucion:
        return nodo_inicial
    else:
        # expandir nodos sucesores (hijos)
        dato_nodo = nodo_inicial.get_datos()
        hijo = [dato_nodo[1], dato_nodo[0], dato_nodo[2], dato_nodo[3]]
        hijo_izquierdo = Nodo(hijo)
        hijo = [dato_nodo[0], dato_nodo[2], dato_nodo[1], dato_nodo[3]]
        hijo_central = Nodo(hijo)
        hijo = [dato_nodo[0], dato_nodo[1], dato_nodo[3], dato_nodo[2]]
        hijo_derecho = Nodo(hijo)

        nodo_inicial.set_hijos([hijo_izquierdo, hijo_central, hijo_derecho])

        for nodo_hijo in nodo_inicial.get_hijos():
            if not nodo_hijo.get_datos() in visitados:
                # llamada recursiva
                sol = buscar_solucion(nodo_hijo, solucion, visitados)
                if sol != None:
                    return sol

if __name__ == "__main__":
    estado_inicial = [4, 2, 3, 1]
    solucion = [1, 2, 3, 4]
    nodo_solucion = None
    visitados = []
    nodo_inicial = Nodo(estado_inicial)
    nodo = buscar_solucion(nodo_inicial, solucion, visitados)

    resultado = []
    while nodo.get_padre() != None:
        resultado.append(nodo.get_datos())
        nodo = nodo.get_padre()

    resultado.append(estado_inicial)
    resultado.reverse()
    print(resultado)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        first, second = ListNode(), ListNode()
        first_ref, second_ref = first, second

        while head:
            if head.val < x:
                first.next = head
                first = first.next
            else:
                second.next = head
                second = second.next

            head = head.next

        first.next = second_ref.next
        second.next = None
        return first_ref.next


from enum import IntEnum

class SpeechPriority(IntEnum):
	#: Indicates that a speech sequence should have normal priority.
	NORMAL = 0
	#: Indicates that a speech sequence should be spoken after the next utterance of lower priority is complete.
	NEXT = 1
	#: Indicates that a speech sequence is very important and should be spoken right now,
	#: interrupting low priority speech.
	#: After it is spoken, interrupted speech will resume.
	#: Note that this does not interrupt previously queued speech at the same priority.
	NOW = 2

#: Easy shorthand for the Speechpriority class
Spri = SpeechPriority
#: The speech priorities ordered from highest to lowest.
SPEECH_PRIORITIES = tuple(reversed(SpeechPriority))


from django.urls import path
from . import views
app_name ='bookili'
urlpatterns = [
    path('',views.Accueil,name='accueil'),
    path('inscription/',views.inscription,name='inscription'),
    path('InscriptionClient/',views.InscriptionClient,name='InscriptionClient'),
    path('connexion/',views.connexion,name='connexion'),
    path('ConnexionClient/',views.ConnexionClient,name='ConnexionClient'),
    path('deconnexion/',views.deconnexion,name='deconnexion'),
    path('features/',views.Accueil,name='features'),
    path('tarifs/',views.Accueil,name='tarifs'),
    path('inscription/structure/',views.CreateStructure,name='structure'),
    path('inscription/structure/service/',views.Service,name='service'),
    path('inscription/structure/service/staff/',views.CreateStaff,name='staff'),
    path('connexion/profile/DetailStructure/<int:id>',views.AfficherStructure,name ='AfficherStructure'),
    path('connexion/profile/DetailStaff/<int:id>',views.AfficherStaff,name ='AfficherStaff'),
    path('profile/',views.Profile,name='Profile'),
    path('proprietaire/',views.All,name='All'),
]


from flask import Flask, jsonify, render_template, request
from model import TransformersModel
from analysis import CountAvgScore, acc, pos_count, pos_count_select
import json
app = Flask(__name__)

model0 = TransformersModel('nlptown/bert-base-multilingual-uncased-sentiment')
info = []
num_layer = 2
@app.route('/_get_sentence')
def get_sentence():
    with open ("all_dataset.json")as f:
        all_dataset = json.load(f)
    return jsonify(all_dataset = all_dataset)
@app.route('/_get_embedding')
def get_embedding():

    for i in range(num_layer):
        model0.setModel(i)
        model0.getModelOutput()
        model0.getDataSetHiddenState(i)
        model0.getDataAttention(level=i,index=1,word_index=0)
        model0.ground_truth()
        model0.classify()
        model0.part_of_speech()

        info.append({"ground":model0.ground_truth_sentiment,
                    "classify":model0.sentiment,
                    "layer":i,
                    "score":model0.score,
                    "attention":model0.attention,
                    })
    with open ('./data/hidden.json') as f:
         hidden0_json = json.load(f)
    with open ('./data/hidden4.json') as f:
         hidden4_json = json.load(f)
    with open ('./data/hidden7.json') as f:
         hidden7_json = json.load(f)
    with open ('./data/hidden12.json') as f:
         hidden12_json = json.load(f)

    return jsonify(result = model0.web_umap(mode="ground",condition1=0,condition2=1),hidden0 = hidden0_json,
                    hidden4 = hidden4_json,hidden7 = hidden7_json,hidden12 = hidden12_json
                   )

@app.route('/_return_select', methods=['POST'])
def return_embedding():
    a = request.form.get("ids")
    print(a)
    a_list = json.loads(a)
    int_list = list(map(int,a_list))
    result = acc(info,int_list,layer=num_layer)["accuracy"]
    score = CountAvgScore(info,int_list,layer=num_layer,key='score')
    attention = CountAvgScore(info,int_list,layer=num_layer,key='attention')
    pos = pos_count_select(select=acc(info,int_list,layer=num_layer)["true_selection"],data=model0.pos,layer= num_layer)

    #for i in range(13):
    #    acc = model0.sentiment_Accuracy(data=int_list)
    #    result.append([acc,i])

    return jsonify(result=result,score=score,attention=attention,pos=pos)

@app.route('/_all_hidden')
def all_projection():
    all_hiddenstate = []
    for i in range(num_layer):
        model0.setModel(i)
        model0.getModelOutput(level=i)
        model0.ground_truth()
        all_hiddenstate.append({
            "embedding":model0.getDataSetHiddenState(i),
            "layer":i})
    model0.set_all_word_embedding(embedding=all_hiddenstate)

    return jsonify(result=model0.web_umap_all())

@app.route('/')
def index():
    return render_template('index.html')
if __name__ =="__main__":
    app.run(debug=True)


import cv2, dlib, argparse
from Face_Recognition_Library import Face_Recognition_Library as frl

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Align faces in image')
    parser.add_argument('input', type=str, help='')
    parser.add_argument('output', type=str, help='')
    parser.add_argument('--scale', metavar='S', type=int, default=1, help='an integer for the accumulator')
    args = parser.parse_args()

    lib = frl()

    input_image = args.input
    output_image = args.output
    scale = args.scale

    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

    img = cv2.imread(input_image, cv2.IMREAD_GRAYSCALE)
    x1, y1 = 384, 185
    x2, y2 = 384, 618
    x3, y3 = 622, 185
    x4, y4 = 622, 618

    x, y = min(x1, x2, x3, x4), min(y1, y2, y3, y4)
    w,h = max(x1, x2, x3, x4) - x, max(y1, y2, y3, y4) - y

    x, y, w, h = [int(i) for i in [x, y, w, h]]
    # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # quit(0)
    height, width = img.shape[:2]
    s_height, s_width = height // scale, width // scale
    img = cv2.resize(img, (s_width, s_height))
    # Resize x, y, w, h
    x, y, w, h = [int(i / scale) for i in [x, y, w, h]]
    # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    # cv2.imshow('img', img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    # dets = detector(img, 1)
    # print(type(dets))
    dets = dlib.rectangles([dlib.rectangle(x, y, x + w, y + h)])
    # print(type(dets))
    # quit()
    # landmarks = predictor(img, dlib.rectangle(x, y, x + w, y + h))
    # quit(0)
    for i, det in enumerate(dets):
        shape = predictor(img, det)
        left_eye = lib.extract_left_eye_center(shape)
        right_eye = lib.extract_right_eye_center(shape)

        M = lib.get_rotation_matrix(left_eye, right_eye)
        rotated = cv2.warpAffine(img, M, (s_width, s_height), flags=cv2.INTER_CUBIC)

        cropped = lib.crop_image(rotated, det)

        if output_image.endswith('.jpg'):
            output_image_path = output_image.replace('.jpg', '_%i.jpg' % i)
        elif output_image.endswith('.png'):
            output_image_path = output_image.replace('.png', '_%i.jpg' % i)
        else:
            output_image_path = output_image + ('_%i.jpg' % i)
        cv2.imwrite(output_image_path, cropped)


import os
from google.appengine.ext import ndb
import time
import jinja2
import webapp2

jinja_env = jinja2.Environment(
	loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
	autoescape=True)

#Generic key used to group Comments into an entitiy group
PARENT_KEY = ndb.Key("Entity","comment_root")

#This is object that will represent the Comments.
#We are using Object Oriented Programming to create objects in order to put
#them in Google's Database .This object inherit Google ndb.Model class

class Comments(ndb.Model):
	"""Model object used to store Comments in the datastore"""
	name = ndb.StringProperty()
	comment = ndb.StringProperty()
	date = ndb.DateTimeProperty(auto_now_add=True)

#Ancestor Query, as shown , are strongly consistent with the high
#Replication Datastore. Query that span entitiy group are eventually consistent.

class ErrorPage(webapp2.RequestHandler):
	def get(self):
		template = jinja_env.get_template("error.html")
		self.response.out.write(template.render())

class MainPage(webapp2.RequestHandler):

    def get(self):
        comment_query = Comments.query(ancestor = PARENT_KEY).order(-Comments.date)
        template = jinja_env.get_template("index.html")
        self.response.write(template.render({"comment_query": comment_query}))

class AddcommentAction(webapp2.RequestHandler):
	def post(self):
# We set the same parent kek on the 'Comments' to
#ensure each Comments is in the same entitiy group.

		next_comment = Comments(parent=PARENT_KEY,
			                    name = self.request.get("name").strip(),
			                    comment = self.request.get("comment").strip())
		if not (next_comment.comment):
			self.redirect(self.request.referer)
			self.redirect("/error")

#Write to the Google Datastore
		else:
		    next_comment.put()
# here redirect and send it back to whoever send him here(referer)
		    self.redirect(self.request.referer)

app = webapp2.WSGIApplication([
	("/", MainPage),
	("/addcomment", AddcommentAction),
	("/error",ErrorPage)
	],debug = True)


from lxml import etree

f= open('test.html', 'r', encoding='utf-8')
data = f.read()

tree = etree.HTML(data)
import json
datas =tree.xpath('//div[@class="item-description"]/div')
for d in datas:
    if len(d)<1:continue
    url = d.xpath("./a/@href")
    title = d.xpath('./text()')
    with open('../text.txt', 'a', encoding='utf-8')as fp:
        fp.write(title[0]+'\r'+url[0]+'\r\n')


#!/usr/bin/python
# coding: utf8

import os
import re

from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements('requirements.txt', session=False)

# reqs is a list of requirement
reqs = [str(ir.req) for ir in install_reqs]

test_requirements = [
    "pytest", "mock"
]

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

# parse version
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
                       'sxapi', "__init__.py")) as fdp:
    pattern = re.compile(r".*__version__ = '(.*?)'", re.S)
    VERSION = pattern.match(fdp.read()).group(1)

config = {
    'description': 'smaXtec API client',
    'author': 'Matthias Wutte',
    'long_description': readme,
    'url': '',
    'download_url': 'https://github.com/wuttem',
    'author_email': 'matthias.wutte@gmail.com',
    'version': VERSION,
    'install_requires': reqs,
    'tests_require': test_requirements,
    'packages': find_packages(),
    'scripts': [],
    'name': 'sxapi'
}

setup(**config)


from MLP_toolbox import Linear, ReLU, Tanh, LossMSE, Sequential
from torch import empty
from torch import randperm  # used for random permutation for training
import math

def compute_nb_errors(prediction, target):
    """
    compute
    :param prediction [N x nb_output]:  tensor containing the model output
    :param target [N], tensor containing the desired target
    :return: number of errors.

    - If the network output is multidimensional, the predicted value corresponds to the unit with maximal activation
    - If the network is one dimensional, the absolute value of abs(prediction-target) should by < 0.5
    """
    nb_errors = 0
    if prediction.size(1)>1:
        # MLP has several units in output layer (use one hot encoding)
        _, predicted_classes = prediction.max(1)
        for k in range(prediction.size(0)):
            if target[k] != predicted_classes[k]:
                nb_errors = nb_errors + 1
    else:
        # prediction has only 1 output (no one hot encoding)
        for k in range(prediction.size(0)):
            if (prediction[k] - target[k]).abs() >= 0.5:
                nb_errors = nb_errors + 1
    return nb_errors

def generate_disc_set(nb_samples):
    """
    :param nb_samples: number of data samples to create
    generate a dataset that contains uniformly distributed samples in [0,1] x [0,1]
    target value is 1 if the distance from the point [0.5], [0.5] is < 1/(2*math.pi)
    NOTE: this dataset is balanced when samples are uniformly distributed
    """
    input = empty((nb_samples, 2)).uniform_(0,1)
    target = input.sub(0.5).pow(2).sum(dim=1).sub(1/(2*math.pi)).sign().add(1).div(2).long()
    target = (-target).add(1)

    return input, target

if __name__ == '__main__':

    # given in the problem statement
    nb_samples = 1000
    nb_input = 2
    nb_output = 1

    # training parameters
    batch_size = 50
    nb_epochs = 25
    learning_rate = 0.1

    # generate and normalize the data
    train_input, train_target = generate_disc_set(nb_samples)
    test_input, test_target = generate_disc_set(nb_samples)
    mu, std = train_input.mean(dim=0), train_input.std()
    train_input.sub_(mu).div_(std)
    test_input.sub_(mu).div_(std)

    # create an MLP
    network = Sequential(    Linear(nb_input,25),
                             ReLU(),
                             Linear(25,25),
                             ReLU(),
                             Linear(25,25),
                             ReLU(),
                             Linear(25,nb_output),
                             Tanh(),
                             LossMSE())

    # TRAINING OF THE NETWORK
    for e in range(nb_epochs):

        indexes = randperm(train_input.size(0))       # random index array without repetition
        acc_loss = 0                                        # accumulated loss for the current epoch
        errors = 0                                          # number of errors for the current epoch

        for b in range(0, train_input.size(0), batch_size):
            # retrieve a shuffled batch
            batch_input = train_input[indexes.narrow(0,b,batch_size)]
            batch_target = train_target[indexes.narrow(0,b,batch_size)]

            # model prediction
            batch_output = network.forward(batch_input)

            # accumulate loss and errors
            loss = network.loss(batch_target)
            errors = errors + compute_nb_errors(batch_output, batch_target)
            acc_loss += loss.item()

            # train the model
            network.backward()
            network.step(learning_rate)

        print("Training epoch {:d}: \t loss value: {:.2f}, \t error rate: {:.2f}%".format(e, acc_loss, errors/nb_samples*100))

    # OUTPUT THE FINAL PERFORMANCE ON THE TRAINING SET
    train_loss = 0
    train_errors = 0

    for b in range(0, train_input.size(0), batch_size):
        # retrieve a shuffled batch
        batch_input = train_input.narrow(0, b, batch_size)
        batch_target = train_target.narrow(0, b, batch_size)

        # model prediction
        batch_output = network.forward(batch_input)

        # accumulate loss and errors
        loss = network.loss(batch_target)
        train_errors = train_errors + compute_nb_errors(batch_output, batch_target)
        train_loss += loss.item()

        # train the model
        network.backward()
        network.step(learning_rate)

    print("-------------------------------------------------------------")
    print("Training dataset: \t Loss: {:.2f} \t error rate: {:.2f}%".format(train_loss, train_errors/nb_samples*100))

    # OUTPUT THE FINAL PERFORMANCE ON THE TESTING SET
    test_loss = 0
    test_errors = 0

    for b in range(0, test_input.size(0), batch_size):
        # retrieve a shuffled batch
        batch_input = test_input.narrow(0, b, batch_size)
        batch_target = test_target.narrow(0, b, batch_size)

        # model prediction
        batch_output = network.forward(batch_input)

        # accumulate loss and errors
        loss = network.loss(batch_target)
        test_errors = test_errors + compute_nb_errors(batch_output, batch_target)
        test_loss += loss.item()

        # train the model
        network.backward()
        network.step(learning_rate)
    print("-------------------------------------------------------------")
    print("Test dataset: \t\t Loss: {:.2f} \t error rate: {:.2f}%".format(test_loss, test_errors / nb_samples * 100))


class Node:
    def __init__(self, initdata):
        self.data = initdata
        self.next = None
        self.prev = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def getPrev(self):
        return self.prev

    def setData(self, newdata):
        self.data = newdata

    def setNext(self, newnext):
        self.next = newnext

    def setPrev(self, newprev):
        self.prev = newprev

class DoubleList:

    def __init__(self):
        self.head = None

    def isEmpty(self):
        if self.head:
            return False

        return True

    def search(self, item):
        current = self.head
        found = False
        while current != None and not found:
            if current.getData() == item:
                found = True
            else:
                current = current.getNext()

        return found

    def size(self):
        size = 0
        if self.head == None:
            return size

        current = self.head
        while current:
            size += 1
            current = current.getNext()

        return size

    def addFront(self, item):
        temp = Node(item)
        temp.setNext(self.head)
        if self.head:
            self.head.setPrev(temp)

        self.head = temp

    def append(self, item):
        current = self.head
        if current == None:
            self.addFront(item)
            return

        while current.getNext():
            current = current.getNext()

        temp = Node(item)
        current.setNext(temp)
        temp.setPrev(current)

    def popFirst(self):
        if self.head == None:
            return self.head

        head_data = self.head.getData()
        self.head = self.head.getNext()
        return head_data

    def popLast(self):
        if self.head == None:
            return self.head

        current = self.head
        while current.getNext():
            current = current.getNext()

        last_data = current.getData()
        current.getPrev().setNext(None)

        return last_data

    def insert_before(self, item, pos):
        if pos == 0:
            self.addFront(item)
            return

        current = self.head
        index = 0
        while index < pos:
            index += 1
            if current.getNext():
                current = current.getNext()

        temp = Node(item)
        prev = current.getPrev()
        temp.setPrev(prev)
        prev.setNext(temp)
        temp.setNext(current)
        current.setPrev(temp)

    def insert_after(self, item, pos):
        current = self.head
        index = 0
        while index < pos:
            index += 1
            if current.getNext():
                current = current.getNext()

        temp = Node(item)
        next = current.getNext()
        temp.setNext(next)
        temp.setPrev(current)
        if next:
            next.setPrev(temp)
        current.setNext(temp)

    def get_node(self, pos):
        current = self.head
        index = 0
        if current == None:
            return None

        while index < pos:
            index += 1
            if current.getNext():
                current = current.getNext()

        return current

    def del_node(self, node: Node):
        current = self.head
        if current == None:
            return

        while current.getNext():
            if node == current:
                next = current.getNext()
                prev = current.getPrev()
                next.setPrev(prev)
                prev.setNext(next)

            current = current.getNext()

    def __str__(self):
        return_string = "["
        current = self.head
        if current == None:
            return "[]"

        while True:
            return_string += str(current.getData())
            current = current.getNext()
            if current == None:
                break

            return_string += ", "

        return return_string + "]"

if __name__ == "__main__":
    mylist = DoubleList()
    print("isEmpty()")
    print(mylist.isEmpty())

    print("addFront(1)")
    mylist.addFront(1)
    print(mylist)

    print("addFront(2)")
    mylist.addFront(2)
    print(mylist)

    print("append(10)")
    mylist.append(10)
    print(mylist)

    print("append(20)")
    mylist.append(20)
    print(mylist)

    print("isEmpty()")
    print(mylist.isEmpty())

    print("search(100)")
    print(mylist.search(100))

    print("search(2)")
    print(mylist.search(2))

    print("size()")
    print(mylist.size())

    print("popFirst()")
    print(mylist.popFirst())
    print(mylist)

    print("popLast()")
    print(mylist.popLast())
    print(mylist)

    print("insert_before(100, 1)")
    mylist.insert_before(100, 1)
    print(mylist)

    print("insert_before(200, 0)")
    mylist.insert_before(200, 0)
    print(mylist)

    print("insert_after(300, 1)")
    mylist.insert_after(300, 1)
    print(mylist)

    print("insert_after(400, 0)")
    mylist.insert_after(400, 0)
    print(mylist)

    print("del_node(node)")
    print("node data = ", end="")
    node = mylist.get_node(2)
    print(node.getData())
    mylist.del_node(node)
    print(mylist)


##############################################################################################
# FILE : ex4.py
# WRITER : Bar Aloni
# EXERCISE : intro2cs ex4 2015-2016
# DESCRIPTION :
# filter_words_list():
# search within  a list or words, for the words that can be the word in
# a pattern given, while excluding the letters the user guessed in word
#  and failed.
# choose_letter():
# according to a supplied patters, checks in a list of words that matches the
# pattern for the most common letter.
# update_word_pattern():
# updates the given pattern according to a word that define the pattern, and
# a supplied letter(that can be or not be in word)/
# run_single_game():
# according to user input get hint or try to platter words in patter. the game.
# main():
# runs the game endless rounds until the user decides to stop the game.
##############################################################################################
import string
import hangman_helper

def filter_words_list(words, pattern, wrong_guess_lst):
    """
    Goes through the words list given and appends (to an empty  list, words2)
    the words that are equal in length to the pattern supplied.
    A new loop goes through the new list (words2), and through items in wrong
    guess list, and appends to a new list (words 3) all words that does not
    include letters from wrong guest list.
    finally a new loop goes through words2 and excludes all words that does
    not have identical letters ,in identical indexes as in pattern,or that
    contains the given letter somewhere else that doesn't appears in pattern.
    :param words: list of words
    :param pattern: current pattern represented by '_' as long as the word
    :param wrong_guess_lst: list of letters that does not appear in word
    :return: A list of possible match: list of words that matches the pattern
    and do not include the characters in wrong guess list, received by
    filtering the words list.

    """
    words2 = []  # empty list1
    words3 = []  # empty list2
    for word in words:
        if len(pattern) == len(word): # comparing length
            words2.append(word)
    for word2 in words2:
        for letter in wrong_guess_lst: # checks for wrong guesses in word
            if letter not in word2:
                words3.append(word2)
    for p in range(len(pattern)):
        if pattern[p].isalpha():  # it the character in pattern is letter
            for word3 in words3:
                if pattern[p] != word3[p] or \
                        pattern.count(pattern[p]) != word3.count(word3[p]):
                # the letter doesn't have the same index in both words
                #num of times the letter appears in both words is not the same
                    words3.remove(word3)
    return words3

def choose_letter(words, pattern):
    """
    Loop that goes over the letters in abc, and counts the times each letter
    appears in a list of words given. With these values i built a dictionary,
    where the key = letter in abc, value = occurrence.
    Then im using max func to find the highest value, ant it's key.
    :param words: A list of words.
    :param pattern: A given pattern.
    :return: The most common letter in list.
    """
    abc_lst = list(string.ascii_lowercase)
    for p in pattern:
        if p in abc_lst:
            abc_lst.remove(p)
            # List of letters a-z without the given letters in pattern
    words_str = ''.join(words)  # To make it possible to use count
    dct = {}
    lst = []
    for letter in abc_lst:
        occurrence = words_str.count(letter)
        dct[letter] = occurrence
        return max(dct, key=dct.get)

def update_word_pattern(word, pattern, letters):
    """
    Turns the Pattern into a list, in order to change it.
    A loop goes through the indices in Word to find a match between the item
    in indices, and Letter supplied, and changes the pattern list accordingly.
    With no match the pattern won't change.
    Then the function converts the pattern list to an unified string and
    returns the original pattern plated with the letter chosen.
    :param word: A string of lower case letters.
    :param pattern: Length of the word, represented by underscores.
    :param letters: A chosen letter.
    :return: the pattern, integrated with the chosen letter at the right place
    """
    pattern = list(pattern)
    for i in range(len(word)):
        if letters == word[i]:
            pattern[i] = letters  # Inserts i to correct place in pattern
    pattern = ''.join(pattern)
    return pattern

def run_single_game(words_list):
    """
    start:
    setting parameters that will help us in iteration.
    iteration:
    loop that runs while the pattern is empty and we didn't pass the
    number of guesses that we shouldn't pass. we ask for input:
    if the input in o place is HINT -  we will call 2 func that will supply
    us a hint.
    if the input in 1st place is a letter we can check all occurrences as
    specified in the ex4 form. the order of 'elif' lets me use simpler
    definitions.
    end:
    if the pattern is full, we win. otherwise we loos (we are past the
    iteration part), Either way we're asked if we want to start another round.
    :param words_list:a list of words
    :return: the game
    """
    word = hangman_helper.get_random_word(words_list)   # Beginning
    wrong_guess_lst = []
    error_count = 0
    pattern = '_'*len(word)
    msg = hangman_helper.DEFAULT_MSG
    while '_' in pattern and error_count < hangman_helper.MAX_ERRORS:
    # Iteration
        hangman_helper.display_state(pattern, error_count, wrong_guess_lst, msg, ask_play= False)
        (i, j) = hangman_helper.get_input()
        if i == hangman_helper.HINT:
                a = filter_words_list(words_list,pattern,wrong_guess_lst)
                hnt = choose_letter(a ,pattern)
                msg = hangman_helper.HINT_MSG + hnt
                hangman_helper.display_state(pattern, error_count, wrong_guess_lst, msg, ask_play= False)
        elif i != hangman_helper.HINT:
                if len(j) != 1 or not j.isalpha() or j.isupper():  # non valid input
                    msg = hangman_helper.NON_VALID_MSG
                elif j in wrong_guess_lst or j in pattern:  # repeated a choice
                    msg = hangman_helper.ALREADY_CHOSEN_MSG + j
                elif j in word: # input in word (easier by previous definitions)
                    pattern = update_word_pattern(word, pattern, j)
                    msg = hangman_helper.DEFAULT_MSG
                elif j not in word: #input not in word
                    wrong_guess_lst.append(j)
                    error_count += 1
                    msg = hangman_helper.DEFAULT_MSG
    if '_' not in pattern and error_count < hangman_helper.MAX_ERRORS:  # End
        # guessed the word without disqualify.
        msg = hangman_helper.WIN_MSG
        hangman_helper.display_state(pattern, error_count, wrong_guess_lst, msg, ask_play=True)
    else: # the pattern is not full and the ran out of errors allowed
        msg = hangman_helper.LOSS_MSG + word
        hangman_helper.display_state(pattern, error_count, wrong_guess_lst, msg, ask_play=True)

def main():
    """
    runs the game endless rounds as ling as the user decides to stop.
    :return: endless rounds in game, until user decide not to
    """
    words = hangman_helper.load_words()
    run_single_game(words)
    play = hangman_helper.get_input()
    while play == (3, True):
        words = hangman_helper.load_words()
        run_single_game(words)
        play = hangman_helper.get_input()

if __name__ == '__main__':
        hangman_helper.start_gui_and_call_main(main)
        hangman_helper.close_gui()


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

import os

def CHK(return_code, *args):
    """
    Check if the return value of the invoked function returned an error.

    The Qmix DLL makes this pretty easy: All errors are indicated by
    negative return values.

    Parameters
    ----------
    return_code : int
        The code returned from a Qmix DLL function.
    args
        All arguments passed to the function ``funcname``.

    Returns
    -------
    return_code : int
        If no error occurred, the originally passed return value is
        returned.

    Raises
    ------
    RuntimeError
        If the DLL function returned an error code.

    """
    if return_code >= 0:
        return return_code
    else:
        from .error import QmixError  # We import here to avoid circularity with error.py
        e = QmixError(return_code)
        error_string = e.error_string
        msg = (error_string + ", Error number: " + str(e.error_number) +
               ", Error code: " + str(e.error_code))
        raise RuntimeError(msg)

def find_dll(dll_dir, dll_filename):
    """
    Try to find the specified DLL.

    If a DLL directory was given, try to find the DLL there.

    If no DLL directory was given, start looking for the DLL in the following
    order:

    - current working directory
    - global DLL search paths (this also respects the PATH
      environment variable)
    - default Qmix SDK installation directory

    Parameters
    ----------
    dll_dir : string or None
        The directory containing the DLLs. Pass `None` to look in the default locations.
    dll_filename : string
        The name of the DLL to find, including filename extension.

    Returns
    -------
    dll_path : string or None
        The path of the DLL, or `None` if the DLL could not be found.

    """
    if not dll_dir:
        # Check current directory.
        if os.path.exists(dll_filename):
            dll_path = dll_filename
            return dll_path

        # Check DLL search paths.
        import win32api
        try:
            win32api.LoadLibrary(dll_filename)
            dll_path = dll_filename
            return dll_path
        except Exception:
            pass

        # Check default installation directory.
        import appdirs
        dll_dir = appdirs.user_data_dir('QmixSDK', '')
        if os.path.exists(os.path.join(dll_dir, dll_filename)):
            dll_path = os.path.join(dll_dir, dll_filename)
            # Add DLL dir to PATH, otherwise we won't be able to load the DLL.
            os.environ['PATH'] += os.pathsep + dll_dir
            return dll_path

        return None
    else:
        if os.path.exists(os.path.join(dll_dir, dll_filename)):
            dll_path = os.path.join(dll_dir, dll_filename)
            # Add DLL dir to PATH, otherwise we won't be able to load the DLL.
            os.environ['PATH'] += os.pathsep + dll_dir
            return dll_path
        else:
            return None


#!/usr/bin/python
#
# Simple module to control the Sparkfun Serial LCD Modules
#
import serial

#
# LCD Constants
#
LCD_BACKLIGHT_OFF = 128
LCD_BACKLIGHT_MAX = 157
LCD_CHARS = 16
LCD_LINES = 2
LCD_LINESTART = [0, 64, 16, 80] # Cursor position starts for 16 character displays
LCD_MAX_CHARS = LCD_CHARS * LCD_LINES

#
# Control characters/commands
#
LCD_BACLKIGHT_CMD = 0x7C
LCD_CMD = 0xFE
LCD_CMD_CLEAR = 0x01
LCD_CMD_CURSORPOS = 0x80
LCD_CMD_MOVRIGHT = 0x14
LCD_CMD_MOVLEFT = 0x10
LCD_CMD_SCRLRIGHT = 0x1C
LCD_CMD_SCRLLEFT = 0x18

class Controller():
    def __init__(self):
        self.backlight = 1.0
        self.connected = False
        self.serialPort = None

    def connect(self, serialPort, baudRate):
        if self.serialPort is not None and self.serialPort.isOpen():
            self.serialPort.close()

        self.serialPort = serial.Serial(port = serialPort, baudrate = baudRate)
        self.serialPort.close()
        self.serialPort.open()

        if self.serialPort.isOpen():
            self.connected = True
            return True
        else:
            self.connected = False
            return False

    def write(self, string):
        if self.connected:
            self.serialPort.write(string)

    def disconnect(self):
        if self.connected:
            self.serialPort.close()

    def clear(self):
        self.write(chr(LCD_CMD) + chr(LCD_CMD_CLEAR))
        self.write(chr(LCD_CMD) + chr(LCD_CMD_CLEAR))

    def setBacklight(self, brightness):
        if brightness < 0:
            brightness = 0
        elif brightness > 1:
            brightness = 1

        self.backlight = brightness
        LCD_newBrightness = int(self.backlight * (BACKLIGHT_MAX - LCD_BACKLIGHT_OFF)) + LCD_BACKLIGHT_OFF
        self.write(chr(LCD_BACLKIGHT_CMD) + chr(newBrightness))

    def setCursorPos(self, pos):
        if pos < 0:
            pos = 0
        elif pos > (LCD_MAX_CHARS - 1):
            pos = (LCD_MAX_CHARS - 1)

        line = int(pos)/int(LCD_CHARS)
        lineStart = LCD_LINESTART[line]
        linePos = pos - line * LCD_CHARS + lineStart

        self.write(chr(LCD_CMD) + chr(LCD_CMD_CURSORPOS + int(linePos)))

    def cursorMoveRight(self, times = 1):
        for dummy in range(times):
            self.write(chr(LCD_CMD) + chr(LCD_CMD_MOVRIGHT))

    def cursorMoveLeft(self, times = 1):
        for dummy in range(times):
            self.write(chr(LCD_CMD) + chr(LCD_CMD_MOVLEFT))

    def cursorScrollRight(self, times = 1):
        for dummy in range(times):
            self.write(chr(LCD_CMD) + chr(LCD_CMD_SCRLRIGHT))

    def cursorScrollLeft(self, times = 1):
        for dummy in range(times):
            self.write(chr(LCD_CMD) + chr(LCD_CMD_SCRLLEFT))

if __name__ == '__main__':
    print('Standalone operation not supported...')


from django.conf.urls import url
from . import views
urlpatterns = [
	url(r'^$', views.index),
	url(r'^main$', views.loginreg),
	url(r'^register$', views.register),
	url(r'^logout$', views.logout),
	url(r'^login$', views.login),
	url(r'^dashboard$', views.dashboard),
	url(r'^additem$', views.additem),
	url(r'^add$', views.add),
	url(r'^wish_items/(?P<iid>\d+)$', views.showitem),
	url(r'^add/(?P<iid>\d+)$', views.addwish),
	url(r'^delete/(?P<iid>\d+)$', views.delete),
	url(r'^remove/(?P<iid>\d+)$', views.remove)
]


import re
from bs4 import BeautifulSoup

with open('trados_opas.html') as opas:
    text = opas.read()

soup = BeautifulSoup(text,'lxml')

divTag = soup.find_all("div", {"id":"TOC"})
indices = dict()

for tag in divTag:
    for link in tag.findAll('a', href=True):
        indices[link.text] = link['href']

indexdiv = '
\n
'

letters = list()

for linkkey in sorted(indices.keys()):
    if linkkey[0] not in letters:
        letters.append(linkkey[0])
        indexdiv += '\n
' + linkkey[0] + '
\n'
    indexdiv += '
' + linkkey + '\n'

indexdiv += '\n
\n
'

with open('alph_index.html','w+') as opas:
    opas.write(indexdiv)

#indices = sorted(indices)
#
#
#
#for idx, index in enumerate(indices):
#    indexdiv += '
'" + index + "\n"
#
#
#indexdiv += '\n
'


total=0
average=0
count=0
max_num=0
min_num=0
input_num=[]
while True:
	num = input("please input a number:")
	if num == 'done':
		break
	else:
		try:
			num = float(num)
			input_num.append(num)
		except:
			print("Invalid input")

for i in input_num:
	total=total+input_num[i]
	count = count +1
average = total/count
max_num=max(input_num)
min_num=min(input_num)
print(max_num,min_num,average)


from __future__ import print_function, division, absolute_import
from functools import partial

import torch
from torch import nn
from torch.nn import functional as F
import torchvision.models as M
import pretrainedmodels
import math
import torch.utils.model_zoo as model_zoo

from .xception import *
from .inceptionv4 import *
from .inceptionresnetv2 import *
from .dpn import *
from .maskLayer import maskLayer

from models.dictLayer import DictLayer
from models.netvlad import NetVladLayer,NetVladLayerV2

from utils import load_model_with_dict_replace,load_model_with_dict,load_model

__all__ = ['SENet', 'senet154', 'se_resnet50', 'se_resnet101', 'se_resnet152',
           'se_resnext50_32x4d', 'se_resnext101_32x4d','vggnetvlad']
from collections import OrderedDict

#===================================================================================================
#===================================================================================================
#basic models
#===================================================================================================
#===================================================================================================
class AvgPool(nn.Module):
    def forward(self, x):
        return F.avg_pool2d(x, x.shape[2:])

#===================================================================================================
#===================================================================================================
#===================================================================================================
def create_net(net_cls, pretrained: bool):
    # if ON_KAGGLE and pretrained:
    #     net = net_cls()
    #     model_name = net_cls.__name__
    #     weights_path = f'../input/{model_name}/{model_name}.pth'
    #     net.load_state_dict(torch.load(weights_path))
    # else:
    net = net_cls(pretrained=pretrained)
    return net

#===================================================================================================
#===================================================================================================
# VGGNet
#===================================================================================================
#===================================================================================================
class VggNetVLAD(nn.Module):
    def __init__(self, net_cls=M.vgg16, pretrained='imagenet', center_num = 64):
        super().__init__()
        basemodel = create_net( net_cls=net_cls, pretrained=pretrained)
        self.net = nn.Sequential(*list(basemodel.features.children())[:-2])
        self.vlad = NetVladLayerV2(num_clusters= center_num, dim = 512)
        self.featLen = center_num*512

    def forward(self, input):
        x = self.net(input)
        x = self.vlad(x)
        return x

    def finetune(self, model_path:str):
        load_model_with_dict(self.net, model_path, 'encoder.', '')
        load_model_with_dict(self.vlad, model_path, 'pool.', '')

    def freeze_net(self):
        for param in self.net.parameters():
            param.requires_grad = False

#===================================================================================================
#===================================================================================================
# CNN Toy
#===================================================================================================
#===================================================================================================
class CnnToyNet(nn.Module):
    def __init__(self, num_classes, img_size=64):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1),
            nn.MaxPool2d(2, 2),
            nn.LeakyReLU(),
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.MaxPool2d(2, 2),
            nn.LeakyReLU(),
            nn.Conv2d(64, 32, kernel_size=1, padding=0),
            nn.LeakyReLU(),
            nn.AvgPool2d(3,2,1)
        )
        self._scale = 8
        self._fc_len = img_size // self._scale * img_size // self._scale * 32

        self.fc1 = nn.Linear(self._fc_len, 128)
        self.fc2 = nn.Linear(128, num_classes)

    def forward(self, input):
        x = self.net(input)
        #         print(x.shape)
        x = x.view(x.shape[0],-1)
        feat1 = self.fc1(x)
        leaky_feat1 = F.leaky_relu(feat1)
        feat2 = self.fc2(leaky_feat1)

        return feat1, feat2

# ===================================================================================================
# ===================================================================================================
# CNN Toy + vlad
# ===================================================================================================
# ===================================================================================================
class CnnVladToyNet(nn.Module):
    def __init__(self, num_classes, img_size=64):
        super().__init__()
        last_conv_ch = 32
        self.net = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1),
            nn.MaxPool2d(2, 2),
            nn.LeakyReLU(),
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.MaxPool2d(2, 2),
            nn.LeakyReLU(),
            nn.Conv2d(64, last_conv_ch, kernel_size=1, padding=0),
            nn.LeakyReLU(),
            nn.AvgPool2d(3, 2, 1)
        )
        self._scale = 8
        # self._fc_len = img_size // self._scale * img_size // self._scale * 32

        self.vlad = NetVladLayer(input_channels=last_conv_ch,centers_num=32)
        self.fc2 = nn.Linear(self.vlad.output_features, num_classes)

    def forward(self, input):
        x = self.net(input)
        feat1 = self.vlad(x)
        feat2 = self.fc2(feat1)

        return feat1, feat2
#===================================================================================================
#===================================================================================================
# ResNet and DenseNet
#===================================================================================================
#===================================================================================================
class ResNet(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False, net_cls=M.resnet50, dropout=False):
        super().__init__()
        self.net = create_net(net_cls, pretrained=pretrained)
        self.net.avgpool = AvgPool()
        if dropout:
            self.net.fc = nn.Sequential(
                nn.Dropout(),
                nn.Linear(self.net.fc.in_features, num_classes),
            )
        else:
            self.net.fc = nn.Linear(self.net.fc.in_features, num_classes)

    #freeze param
    def freeze(self):
        for param in self.net.parameters():
            param.requires_grad = False

    def fresh_params(self):
        return self.net.fc.parameters()

    def forward(self, x):
        return self.net(x)

#my_model = nn.Sequential(*list(pretrained_model.children())[:-1])
#resnet+1024fc+128fc+softmax
class ResNetV2(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False, net_cls=M.resnet50, dropout=False,fc_dim = 1024):
        super(ResNetV2,self).__init__()
        self.net = create_net(net_cls, pretrained=pretrained)
        self.net.avgpool = AvgPool()
        if dropout:
            self.net.fc = nn.Sequential(
                nn.Linear(self.net.fc.in_features, fc_dim),
                nn.Dropout(),
                nn.ReLU(),
            )
        else:
            self.net.fc = nn.Sequential(
                nn.Linear(self.net.fc.in_features, fc_dim),
                nn.ReLU(),
                )

        self.last_fc = nn.Linear(fc_dim, num_classes)

    #freeze param
    def freeze(self):
        for param in self.net.parameters():
            param.requires_grad = False

    def fresh_params(self):
        return self.net.fc.parameters()

    def forward(self, x):
        fc1 = self.net(x)
        fc2 = self.last_fc(fc1)
        return fc1,fc2

class ResNetV3(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False, net_cls=M.resnet50, dropout=False,fc_dim_per_class = 10):
        super(ResNetV3,self).__init__()
        self.net = create_net(net_cls, pretrained=pretrained)
        self.net.avgpool = AvgPool()

        if dropout:
            self.net.fc = nn.Sequential(
                nn.Linear(self.net.fc.in_features, 1024),
                nn.Dropout(),
                nn.ReLU(),
            )
        else:
            self.net.fc = nn.Sequential(
                nn.Linear(self.net.fc.in_features, 1024),
                nn.ReLU(),
                )

        self.dict_layer = DictLayer( 1024,  fc_dim_per_class*num_classes , num_classes,alpha=0.1)
        self.last_layer = nn.Linear(fc_dim_per_class*num_classes, num_classes)

    #freeze param
    def freeze(self):
        for param in self.net.parameters():
            param.requires_grad = False

    def fresh_params(self):
        return self.net.fc.parameters()

    def forward(self, x, targets):
        fc1 = self.net(x)
        fc2 = self.dict_layer(fc1,targets)
        fc3 = self.last_layer(fc2)
        loss = self.dict_layer.getLoss()
        return fc2,fc3,loss

class ResNetV4(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False,net_cls=M.resnet50, dropout=False):
        super(ResNetV4,self).__init__()
        self.net = create_net(net_cls, pretrained=pretrained)
        self.net.avgpool = AvgPool()
        if dropout:
            self.net.fc = nn.Sequential(
                nn.Linear(self.net.fc.in_features, 1024),
                nn.Dropout(),
                nn.LeakyReLU(),
            )
        else:
            self.net.fc = nn.Sequential(
                nn.Linear(self.net.fc.in_features, 1024),
                nn.LeakyReLU(),
            )

        self.fc_layer = nn.Linear(1024, 1024)
        self.last_layer = nn.Linear(1024, num_classes)

    #freeze param
    def freeze(self):
        for param in self.net.parameters():
            param.requires_grad = False

    def fresh_params(self):
        return self.net.fc.parameters()

    def forward(self, x):
        fc1 = self.net(x)
        fc2 = self.fc_layer(fc1)
        fc2 = F.leaky_relu(fc2)
        fc3 = self.last_layer(fc2)
        return fc2,fc3

    def finetuning(self,num_classes):
        #only change the last layer
        self.last_layer = nn.Linear(1024,num_classes)

# model.classifier = nn.Sequential(*[model.classifier[i] for i in range(4)])
# print(model.classifier)
# model.classifier = nn.Sequential(*list(model.classifier.children())[:-3])
class ResNetVlad(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False, net_cls=M.resnet50, dropout=False, centerK = 32):
        super(ResNetVlad, self).__init__()
        self.net = create_net(net_cls, pretrained=pretrained)
        self.net = nn.Sequential(*list(self.net.children())[:-2]) #get rid of last 2 layer, and conv is last layer

        self.conv = nn.Conv2d(512,64,(1,1))
        self.netvlad = NetVladLayer(64,centers_num=centerK)
        self.netvladlen = self.netvlad.output_features
        self.last_layer = nn.Linear(self.netvladlen,num_classes)

    # freeze param
    def freeze(self):
        for param in self.net.parameters():
            param.requires_grad = False

    def fresh_params(self):
        return list(self.netvlad.parameters(),self.net.last_layer.parameters())

    def forward(self, x):
        fc1 = self.net(x)
        fc1 = self.conv(fc1)
        fc1 = F.leaky_relu(fc1)

        netvladfeat = self.netvlad(fc1)

        clsfeat = self.last_layer(netvladfeat)
        return netvladfeat, clsfeat

    def finetuning(self, num_classes):
        # only change the last layer
        self.last_layer = nn.Linear(self.netvladlen, num_classes)

##======================================================================================================================
##ResNet50 + BBox from Alibaba Image Search
##======================================================================================================================
class ResNetBBoxMask(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False,net_cls=M.resnet50):
        super(ResNetBBoxMask,self).__init__()
        self.netBBox = create_net(net_cls, pretrained=pretrained)
        self.netBBox.avgpool = AvgPool()
        self.netBBox.fc = nn.Linear(self.netBBox.fc.in_features, 4)

        self.mask_layer = maskLayer()

        self.netCls = create_net(net_cls, pretrained=pretrained)
        self.netCls.avgpool = AvgPool()
        self.netCls.fc = nn.Sequential(
            nn.Linear(self.netCls.fc.in_features, 1024),
            nn.LeakyReLU(),
        )
        self.fc_layer = nn.Linear(1024, 1024)
        self.last_layer = nn.Linear(1024, num_classes)

    def forward(self, x):
        bbox = self.netBBox(x)
        bbox = torch.sigmoid(bbox)

        x_hat = self.mask_layer(bbox,x.shape[3])
        x_hat = x_hat.expand(-1,3,-1,-1)

        next_x = x*x_hat

        fc1 = self.netCls(next_x)
        fc2 = self.fc_layer(fc1)
        fc2 = F.leaky_relu(fc2)
        fc3 = self.last_layer(fc2)
        return fc2,fc3,bbox,x_hat

    def fresh_params(self):
        return self.last_layer.parameters()

    def finetuning(self,num_classes):
        #only change the last layer
        self.last_layer = nn.Linear(1024,num_classes)

class DenseNet(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False, net_cls=M.densenet121):
        super().__init__()
        self.net = create_net(net_cls, pretrained=pretrained)
        self.avg_pool = AvgPool()
        self.net.classifier = nn.Linear(
            self.net.classifier.in_features, num_classes)

    def fresh_params(self):
        return self.net.classifier.parameters()

    def forward(self, x):
        out = self.net.features(x)
        out = F.relu(out, inplace=True)
        out = self.avg_pool(out).view(out.size(0), -1)
        out = self.net.classifier(out)
        return out

class DenseNetV2(nn.Module):
    def __init__(self, num_classes,
                 pretrained=False, net_cls=M.densenet121,dropout=False):
        super().__init__()
        self.net = create_net(net_cls, pretrained=pretrained)
        self.avg_pool = AvgPool()
        # self.net.classifier = nn.Linear(
        #     self.net.classifier.in_features, num_classes)
        if dropout:
            self.net.classifier = nn.Sequential(
                nn.Linear(self.net.classifier.in_features, 1024),
                nn.Dropout(),
                nn.LeakyReLU(),
            )
        else:
            self.net.classifier = nn.Sequential(
                nn.Linear(self.net.classifier.in_features, 1024),
                nn.LeakyReLU(),
            )

        self.fc_layer = nn.Linear(1024, 1024)
        self.last_layer = nn.Linear(1024, num_classes)

    def fresh_params(self):
        return self.net.classifier.parameters()

    def forward(self, x):
        out = self.net.features(x)
        out = F.relu(out, inplace=True)
        out = self.avg_pool(out).view(out.size(0), -1)
        out = self.net.classifier(out)
        out = self.fc_layer(out)
        fc2 = F.leaky_relu(out)
        out = self.last_layer(fc2)
        return out

    def finetuning(self,num_classes):
        #only change the last layer
        self.last_layer = nn.Linear(1024,num_classes)

"""
ResNet code gently borrowed from
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
"""

pretrained_settings = {
    'senet154': {
        'imagenet': {
            'url': 'http://data.lip6.fr/cadene/pretrainedmodels/senet154-c7b49a05.pth',
            'input_space': 'RGB',
            'input_size': [3, 224, 224],
            'input_range': [0, 1],
            'mean': [0.485, 0.456, 0.406],
            'std': [0.229, 0.224, 0.225],
            'num_classes': 1000
        }
    },
    'se_resnet50': {
        'imagenet': {
            'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet50-ce0d4300.pth',
            'input_space': 'RGB',
            'input_size': [3, 224, 224],
            'input_range': [0, 1],
            'mean': [0.485, 0.456, 0.406],
            'std': [0.229, 0.224, 0.225],
            'num_classes': 1000
        }
    },
    'se_resnet101': {
        'imagenet': {
            'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet101-7e38fcc6.pth',
            'input_space': 'RGB',
            'input_size': [3, 224, 224],
            'input_range': [0, 1],
            'mean': [0.485, 0.456, 0.406],
            'std': [0.229, 0.224, 0.225],
            'num_classes': 1000
        }
    },
    'se_resnet152': {
        'imagenet': {
            'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet152-d17c99b7.pth',
            'input_space': 'RGB',
            'input_size': [3, 224, 224],
            'input_range': [0, 1],
            'mean': [0.485, 0.456, 0.406],
            'std': [0.229, 0.224, 0.225],
            'num_classes': 1000
        }
    },
    'se_resnext50_32x4d': {
        'imagenet': {
            'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext50_32x4d-a260b3a4.pth',
            'input_space': 'RGB',
            'input_size': [3, 224, 224],
            'input_range': [0, 1],
            'mean': [0.485, 0.456, 0.406],
            'std': [0.229, 0.224, 0.225],
            'num_classes': 1000
        }
    },
    'se_resnext101_32x4d': {
        'imagenet': {
            'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext101_32x4d-3b2fe3d8.pth',
            'input_space': 'RGB',
            'input_size': [3, 224, 224],
            'input_range': [0, 1],
            'mean': [0.485, 0.456, 0.406],
            'std': [0.229, 0.224, 0.225],
            'num_classes': 1000
        }
    },
}

class SEModule(nn.Module):

    def __init__(self, channels, reduction):
        super(SEModule, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1,
                             padding=0)
        self.relu = nn.ReLU(inplace=True)
        self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1,
                             padding=0)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        module_input = x
        x = self.avg_pool(x)
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        x = self.sigmoid(x)
        return module_input * x

class Bottleneck(nn.Module):
    """
    Base class for bottlenecks that implements `forward()` method.
    """
    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out = self.se_module(out) + residual
        out = self.relu(out)

        return out

class SEBottleneck(Bottleneck):
    """
    Bottleneck for SENet154.
    """
    expansion = 4

    def __init__(self, inplanes, planes, groups, reduction, stride=1,
                 downsample=None):
        super(SEBottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes * 2, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes * 2)
        self.conv2 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3,
                               stride=stride, padding=1, groups=groups,
                               bias=False)
        self.bn2 = nn.BatchNorm2d(planes * 4)
        self.conv3 = nn.Conv2d(planes * 4, planes * 4, kernel_size=1,
                               bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.se_module = SEModule(planes * 4, reduction=reduction)
        self.downsample = downsample
        self.stride = stride

class SEResNetBottleneck(Bottleneck):
    """
    ResNet bottleneck with a Squeeze-and-Excitation module. It follows Caffe
    implementation and uses `stride=stride` in `conv1` and not in `conv2`
    (the latter is used in the torchvision implementation of ResNet).
    """
    expansion = 4

    def __init__(self, inplanes, planes, groups, reduction, stride=1,
                 downsample=None):
        super(SEResNetBottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False,
                               stride=stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1,
                               groups=groups, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.se_module = SEModule(planes * 4, reduction=reduction)
        self.downsample = downsample
        self.stride = stride

class SEResNeXtBottleneck(Bottleneck):
    """
    ResNeXt bottleneck type C with a Squeeze-and-Excitation module.
    """
    expansion = 4

    def __init__(self, inplanes, planes, groups, reduction, stride=1,
                 downsample=None, base_width=4):
        super(SEResNeXtBottleneck, self).__init__()
        width = int(math.floor(planes * (base_width / 64)) * groups)

        self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, stride=1, bias=False)
        self.bn1 = nn.BatchNorm2d(width)
        self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride,
                               padding=1, groups=groups, bias=False)
        self.bn2 = nn.BatchNorm2d(width)
        self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.se_module = SEModule(planes * 4, reduction=reduction)
        self.downsample = downsample
        self.stride = stride

class SENet(nn.Module):

    def __init__(self, block, layers, groups, reduction, dropout_p=0.2,
                 inplanes=128, input_3x3=True, downsample_kernel_size=3,
                 downsample_padding=1, num_classes=1000):
        """
        Parameters
        ----------
        block (nn.Module): Bottleneck class.
            - For SENet154: SEBottleneck
            - For SE-ResNet models: SEResNetBottleneck
            - For SE-ResNeXt models:  SEResNeXtBottleneck
        layers (list of ints): Number of residual blocks for 4 layers of the
            network (layer1...layer4).
        groups (int): Number of groups for the 3x3 convolution in each
            bottleneck block.
            - For SENet154: 64
            - For SE-ResNet models: 1
            - For SE-ResNeXt models:  32
        reduction (int): Reduction ratio for Squeeze-and-Excitation modules.
            - For all models: 16
        dropout_p (float or None): Drop probability for the Dropout layer.
            If `None` the Dropout layer is not used.
            - For SENet154: 0.2
            - For SE-ResNet models: None
            - For SE-ResNeXt models: None
        inplanes (int):  Number of input channels for layer1.
            - For SENet154: 128
            - For SE-ResNet models: 64
            - For SE-ResNeXt models: 64
        input_3x3 (bool): If `True`, use three 3x3 convolutions instead of
            a single 7x7 convolution in layer0.
            - For SENet154: True
            - For SE-ResNet models: False
            - For SE-ResNeXt models: False
        downsample_kernel_size (int): Kernel size for downsampling convolutions
            in layer2, layer3 and layer4.
            - For SENet154: 3
            - For SE-ResNet models: 1
            - For SE-ResNeXt models: 1
        downsample_padding (int): Padding for downsampling convolutions in
            layer2, layer3 and layer4.
            - For SENet154: 1
            - For SE-ResNet models: 0
            - For SE-ResNeXt models: 0
        num_classes (int): Number of outputs in `last_linear` layer.
            - For all models: 1000
        """
        super(SENet, self).__init__()
        self.inplanes = inplanes
        if input_3x3:
            layer0_modules = [
                ('conv1', nn.Conv2d(3, 64, 3, stride=2, padding=1,
                                    bias=False)),
                ('bn1', nn.BatchNorm2d(64)),
                ('relu1', nn.ReLU(inplace=True)),
                ('conv2', nn.Conv2d(64, 64, 3, stride=1, padding=1,
                                    bias=False)),
                ('bn2', nn.BatchNorm2d(64)),
                ('relu2', nn.ReLU(inplace=True)),
                ('conv3', nn.Conv2d(64, inplanes, 3, stride=1, padding=1,
                                    bias=False)),
                ('bn3', nn.BatchNorm2d(inplanes)),
                ('relu3', nn.ReLU(inplace=True)),
            ]
        else:
            layer0_modules = [
                ('conv1', nn.Conv2d(3, inplanes, kernel_size=7, stride=2,
                                    padding=3, bias=False)),
                ('bn1', nn.BatchNorm2d(inplanes)),
                ('relu1', nn.ReLU(inplace=True)),
            ]
        # To preserve compatibility with Caffe weights `ceil_mode=True`
        # is used instead of `padding=1`.
        layer0_modules.append(('pool', nn.MaxPool2d(3, stride=2,
                                                    ceil_mode=True)))
        self.layer0 = nn.Sequential(OrderedDict(layer0_modules))
        self.layer1 = self._make_layer(
            block,
            planes=64,
            blocks=layers[0],
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=1,
            downsample_padding=0
        )
        self.layer2 = self._make_layer(
            block,
            planes=128,
            blocks=layers[1],
            stride=2,
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=downsample_kernel_size,
            downsample_padding=downsample_padding
        )
        self.layer3 = self._make_layer(
            block,
            planes=256,
            blocks=layers[2],
            stride=2,
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=downsample_kernel_size,
            downsample_padding=downsample_padding
        )
        self.layer4 = self._make_layer(
            block,
            planes=512,
            blocks=layers[3],
            stride=2,
            groups=groups,
            reduction=reduction,
            downsample_kernel_size=downsample_kernel_size,
            downsample_padding=downsample_padding
        )

        self.avg_pool = AvgPool()
        self.dropout = nn.Dropout(dropout_p) if dropout_p is not None else None
        self.last_linear = nn.Linear(512 * block.expansion, num_classes)

    def _make_layer(self, block, planes, blocks, groups, reduction, stride=1,
                    downsample_kernel_size=1, downsample_padding=0):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=downsample_kernel_size, stride=stride,
                          padding=downsample_padding, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, groups, reduction, stride,
                            downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes, groups, reduction))

        return nn.Sequential(*layers)

    def features(self, x):

        x = self.layer0(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        return x

    def logits(self, x):
        x = self.avg_pool(x)
        if self.dropout is not None:
            x = self.dropout(x)
        x = x.view(x.size(0), -1)
        x = self.last_linear(x)
        return x

    def forward(self, x):
        x = self.features(x)
        x = self.logits(x)
        return x

def initialize_pretrained_model(model, num_classes, settings):
    # assert num_classes == settings['num_classes'], \
    #     'num_classes should be {}, but is {}'.format(
    #         settings['num_classes'], num_classes)

    pretrained_dict = model_zoo.load_url(settings['url'])
    model_dict = model.state_dict()

    # 将pretrained_dict里不属于model_dict的键剔除掉
    pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict and 'last_linear' not in k}
    # pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}

    # 更新现有的model_dict
    model_dict.update(pretrained_dict)
    # 加载我们真正需要的state_dict
    model.load_state_dict(model_dict)

    model.input_space = settings['input_space']
    model.input_size = settings['input_size']
    model.input_range = settings['input_range']
    model.mean = settings['mean']
    model.std = settings['std']

def senet154(num_classes=1000, pretrained='imagenet'):
    model = SENet(SEBottleneck, [3, 8, 36, 3], groups=64, reduction=16,
                  dropout_p=0.2, num_classes=num_classes)
    if pretrained is not None:
        settings = pretrained_settings['senet154'][pretrained]
        initialize_pretrained_model(model, num_classes, settings)
    return model

def se_resnet50(num_classes=1000, pretrained='imagenet'):
    model = SENet(SEResNetBottleneck, [3, 4, 6, 3], groups=1, reduction=16,
                  dropout_p=None, inplanes=64, input_3x3=False,
                  downsample_kernel_size=1, downsample_padding=0,
                  num_classes=num_classes)
    if pretrained is not None:
        settings = pretrained_settings['se_resnet50'][pretrained]
        initialize_pretrained_model(model, num_classes, settings)
    return model

def se_resnet101(num_classes=1000, pretrained='imagenet'):
    model = SENet(SEResNetBottleneck, [3, 4, 23, 3], groups=1, reduction=16,
                  dropout_p=None, inplanes=64, input_3x3=False,
                  downsample_kernel_size=1, downsample_padding=0,
                  num_classes=num_classes)
    if pretrained is not None:
        settings = pretrained_settings['se_resnet101'][pretrained]
        initialize_pretrained_model(model, num_classes, settings)
    return model

def se_resnet152(num_classes=1000, pretrained='imagenet'):
    model = SENet(SEResNetBottleneck, [3, 8, 36, 3], groups=1, reduction=16,
                  dropout_p=None, inplanes=64, input_3x3=False,
                  downsample_kernel_size=1, downsample_padding=0,
                  num_classes=num_classes)
    if pretrained is not None:
        settings = pretrained_settings['se_resnet152'][pretrained]
        initialize_pretrained_model(model, num_classes, settings)
    return model

def se_resnext50_32x4d(num_classes=1000, pretrained='imagenet'):
    model = SENet(SEResNeXtBottleneck, [3, 4, 6, 3], groups=32, reduction=16,
                  dropout_p=None, inplanes=64, input_3x3=False,
                  downsample_kernel_size=1, downsample_padding=0,
                  num_classes=num_classes)
    if pretrained is not None:
        settings = pretrained_settings['se_resnext50_32x4d'][pretrained]
        initialize_pretrained_model(model, num_classes, settings)
    return model

def se_resnext101_32x4d(num_classes=1000, pretrained='imagenet'):
    model = SENet(SEResNeXtBottleneck, [3, 4, 23, 3], groups=32, reduction=16,
                  dropout_p=None, inplanes=64, input_3x3=False,
                  downsample_kernel_size=1, downsample_padding=0,
                  num_classes=num_classes)

    if pretrained is not None:
        settings = pretrained_settings['se_resnext101_32x4d'][pretrained]
        initialize_pretrained_model(model, num_classes, settings)
    return model

class SE50MSC(nn.Module):

    def __init__(self, num_classes=1000, pretrained='imagenet'):
        super(SE50MSC, self).__init__()
        self.basemodel = se_resnext50_32x4d(num_classes=num_classes, pretrained='imagenet')
        self.basemodel.layer0.conv1 = nn.Sequential()
        self.basemodel.layer0.bn1 = nn.Sequential()

        self.MSC_5x5 = nn.Conv2d(3, 32, 5, stride=2, padding=2, bias=False)
        self.MSC_7x7 = nn.Conv2d(3, 32, 7, stride=2, padding=3, bias=False)
        self.MSC_9x9 = nn.Conv2d(3, 32, 9, stride=2, padding=4, bias=False)
        self.MSC_bn = nn.BatchNorm2d(96)

        self.MSC_conv1x1 = nn.Conv2d(96, 64, 1, stride=1, bias=False)
        self.MSC_conv1x1_bn = nn.BatchNorm2d(64)

    def forward(self, x):
        MSC_5x5 = self.MSC_5x5(x)
        MSC_7x7 = self.MSC_7x7(x)
        MSC_9x9 = self.MSC_9x9(x)
        x = torch.cat([MSC_5x5,MSC_7x7,MSC_9x9],dim=1)

        x = F.relu(self.MSC_bn(x))
        x = self.MSC_conv1x1(x)
        x = F.relu(self.MSC_conv1x1_bn(x))
        x = self.basemodel(x)
        return x

se_resnext50_msc = partial(SE50MSC)
se_resnext50 = partial(se_resnext50_32x4d)
se_resnext101 = partial(se_resnext101_32x4d)
se_resnet152 = partial(se_resnet152)
inception_v4 = partial(inceptionv4)
inception_v4_netvlad = partial(inceptionv4_netvlad)
inception_v4_attention = partial(inceptionv4_attention)
vggnetvlad = partial(VggNetVLAD)

inceptionresnet_v2 = partial(inceptionresnetv2)
dpn_92 = partial(dpn92)
dpn_68b = partial(dpn68b)

resnet18 = partial(ResNet, net_cls=M.resnet18)
resnetvlad18 = partial(ResNetVlad,net_cls=M.resnet18)
resnet18V4 = partial(ResNetV4, net_cls=M.resnet18)
resnet34 = partial(ResNet, net_cls=M.resnet34)
resnet50 = partial(ResNet, net_cls=M.resnet50)
resnet50V2 = partial(ResNetV2, net_cls=M.resnet50)
resnet50V3 = partial(ResNetV3, net_cls=M.resnet50)
resnet50V4 = partial(ResNetV4, net_cls=M.resnet50)
resnet101 = partial(ResNet, net_cls=M.resnet101)
resnet152 = partial(ResNet, net_cls=M.resnet152)

densenet121 = partial(DenseNet, net_cls=M.densenet121)
densenet169 = partial(DenseNet, net_cls=M.densenet169)
densenet201 = partial(DenseNet, net_cls=M.densenet201)
densenet161 = partial(DenseNet, net_cls=M.densenet161)

cnntoynet = partial(CnnToyNet)
cnnvladtoynet = partial(CnnVladToyNet)


N = int(input("Enter an integer: "))

evenSum = 0

#loop will continue until i is equal to N i.e. until i < N+1
for i in range(1, N+1):
	#if i is divisible by 2 the it is even number
	if(i % 2 == 0):
		#adding i to the evenSum
		evenSum += i
	#increment i
	i += 1
#printing result
print("Sum of all even number between 1 and %d = %d"%(N, evenSum))


import copy
import os
from collections import OrderedDict

import numpy as np

from imagesplit.file.data_type import DataType
from imagesplit.file.file_image_descriptor import FileImageDescriptor
from imagesplit.file.file_wrapper import FileWrapper, FileStreamer
from imagesplit.file.image_file_reader import LinearImageFileReader
from imagesplit.image.combined_image import Axis
from imagesplit.utils.utilities import compute_bytes_per_voxel, \
    get_numpy_datatype

class MetaIoFile(LinearImageFileReader):
    """A class for reading or writing 3D imaging data to/from a MetaIO file
    pair (.mhd and .raw). """

    # pylint: disable=too-many-instance-attributes, super-with-arguments

    def __init__(self, local_file_size, header_filename,
                 file_handle_factory, header_template):
        super(MetaIoFile, self).__init__(local_file_size)
        self._file_handle_factory = file_handle_factory
        self._header_filename = header_filename
        self._input_path = os.path.dirname(os.path.abspath(header_filename))
        self._file_wrapper = None
        self._file_streamer = None
        if header_template:
            # File is for writing
            self._mode = 'wb'
            # Force the raw filename to match the header filename
            base_filename = os.path.splitext(
                os.path.basename(header_filename))[0]
            header = copy.deepcopy(header_template)
            header['ElementDataFile'] = base_filename + '.raw'

            save_mhd_header(header_filename, header)
            self._header = header

        else:
            # File is for reading
            self._mode = 'rb'
            self._header = load_mhd_header(header_filename)

        self._bytes_per_voxel = compute_bytes_per_voxel(
            self._header["ElementType"]) # ToDo: set this based on output format
        self._numpy_format = get_numpy_datatype(
            self._header["ElementType"],
            self._header["BinaryDataByteOrderMSB"])
        self._subimage_size = self._header["DimSize"]
        self._dimension_ordering = get_condensed_dim_order(self._header)

    @classmethod
    def load_and_parse_header(cls, filename):
        """Reads a MetaIO header file and parses"""

        header = load_mhd_header(filename)
        return parse_mhd(header)

    @classmethod
    def create_read_file(cls, subimage_descriptor, file_handle_factory):
        """Create a MetaIoFile class for writing"""

        filename = subimage_descriptor.filename
        local_file_size = subimage_descriptor.ranges.image_size
        return cls(local_file_size, filename, file_handle_factory, None)

    @classmethod
    def create_write_file(cls, subimage_descriptor, file_handle_factory):
        """Create a MetaIoFile class for this filename and template"""

        header_template = cls._create_meta_header(subimage_descriptor)
        # header_template = copy.deepcopy(subimage_descriptor.template)
        local_file_size = subimage_descriptor.get_local_size()
        local_origin = subimage_descriptor.get_local_origin()

        if subimage_descriptor.data_type:
            header_template["ElementType"] = \
                DataType.metaio_from_name(subimage_descriptor.data_type)
        header_template["DimSize"] = local_file_size
        header_template["Origin"] = local_origin
        filename = subimage_descriptor.filename
        return cls(local_file_size, filename, file_handle_factory,
                   header_template)

    def close_file(self):
        """Close file"""
        self.close()

    def write_line(self, start_coords, image_line, rescale_limits):
        """Write consecutive voxels to the raw binary file."""

        return self._get_file_streamer().write_line(
            start_coords, image_line, rescale_limits)

    def read_line(self, start_coords, num_voxels_to_read):
        """Read consecutive voxels of image data from the raw binary file
        starting at the specified coordinates. """

        return self._get_file_streamer().read_line(start_coords,
                                                   num_voxels_to_read)

    def get_bytes_per_voxel(self):
        """Return the number of bytes used to represent a single voxel in
        this image. """

        header = self._get_header()
        return compute_bytes_per_voxel(header["ElementType"])

    def get_dimension_ordering(self):
        """
        Return the preferred dimension ordering for writing data.

        Returns an array of 3 element, where each element represents a
        dimension in the global coordinate system numbered from 1 to 3 and
        is positive if data are to be written in ascending coordinates (in
        the global system) or negative if to be written in descending global
        coordinates along that dimension
        """

        return self._dimension_ordering

    @classmethod
    def _create_meta_header(cls, subimage_descriptor):
        local_file_size = subimage_descriptor.get_local_size()
        local_origin = subimage_descriptor.get_local_origin()
        local_voxel_size = subimage_descriptor.get_local_voxel_size()

        transform_matrix = condensed_to_cosine(
            subimage_descriptor.axis.to_condensed_format())

        header = get_default_metadata()
        header["ObjectType"] = 'Image'
        header["NDims"] = np.size(local_file_size)
        header["BinaryData"] = 'True'
        header["BinaryDataByteOrderMSB"] = subimage_descriptor.msb
        header["CompressedData"] = 'False'
        header["TransformMatrix"] = transform_matrix
        header["ElementSize"] = local_voxel_size
        header["DimSize"] = local_file_size
        header["ElementType"] = \
            DataType.metaio_from_name(subimage_descriptor.data_type)
        header["Origin"] = local_origin

        return header

    def _get_header(self):
        """Return an OrderedDict containing the MetaIO metaheader metadata
        for this image. """

        if not self._header:
            self._header = load_mhd_header(self._header_filename)
        return self._header

    def _get_file_wrapper(self):
        """Return the FileWrapper representing this image, creating it if
        it does not already exist. """

        if not self._file_wrapper:
            header = self._get_header()
            filename_raw = os.path.join(self._input_path,
                                        header["ElementDataFile"])
            self._file_wrapper = FileWrapper(filename_raw,
                                             self._file_handle_factory,
                                             self._mode)
        return self._file_wrapper

    def _get_file_streamer(self):
        """Return the FileStreamer representing this image, creating it
        if it does not already exist. """

        if not self._file_streamer:
            self._file_streamer = FileStreamer(self._get_file_wrapper(),
                                               self._subimage_size,
                                               self._bytes_per_voxel,
                                               self._numpy_format,
                                               self._dimension_ordering)
        return self._file_streamer

    def close(self):
        """Close the files associated with this image, if they are not
        already closed. """

        if self._file_streamer:
            self._file_streamer.close()
            self._file_streamer = None
        if self._file_wrapper:
            self._file_wrapper.close()
            self._file_wrapper = None

def load_mhd_header(filename):
    """Return an OrderedDict containing metadata loaded from an mhd file."""

    metadata = OrderedDict()

    with open(filename) as header_file:
        for line in header_file:
            (key, val) = [x.strip() for x in line.split("=")]
            if key in ['ElementSpacing', 'Offset', 'CenterOfRotation',
                       'TransformMatrix', 'ElementSize']:
                new_val = [float(s) for s in val.split()]
            elif key in ['NDims', 'ElementNumberOfChannels']:
                new_val = int(val)
            elif key in ['DimSize']:
                new_val = [int(s) for s in val.split()]
            elif key in ['BinaryData', 'BinaryDataByteOrderMSB',
                         'CompressedData']:
                # pylint: disable=simplifiable-if-statement
                if val.lower() == "true":
                    new_val = True
                else:
                    new_val = False
            else:
                new_val = val

            metadata[key] = new_val

    return metadata

def save_mhd_header(filename, metadata):
    """Saves a mhd header file to disk using the given metadata"""

    # Add default metadata, replacing with custom specified values
    header = ''
    default_metadata = get_default_metadata()
    for key, val in default_metadata.items():
        if key in metadata.keys():
            value = metadata[key]
        else:
            value = val
        if value or value == 'False' or value == 0:
            value = str(value)
            value = value.replace("[", "").replace("]", "").replace(",", "")
            header += '%s = %s\n' % (key, value)

    # Add any custom metadata tags
    for key, val in metadata.items():
        if key not in default_metadata.keys():
            value = str(metadata[key])
            value = value.replace("[", "").replace("]", "").replace(",", "")
            header += '%s = %s\n' % (key, value)

    file_handle = open(filename, 'w')
    file_handle.write(header)
    file_handle.close()

def get_default_metadata():
    """Return an OrderedDict containing default mhd file metadata"""

    return OrderedDict(
        [('ObjectType', 'Image'), ('NDims', '3'), ('BinaryData', 'True'),
         ('BinaryDataByteOrderMSB', 'True'),
         ('CompressedData', []), ('CompressedDataSize', []),
         ('TransformMatrix', []), ('Offset', []),
         ('CenterOfRotation', []), ('AnatomicalOrientation', []),
         ('ElementSpacing', []), ('DimSize', []),
         ('ElementNumberOfChannels', []), ('ElementSize', []),
         ('ElementType', 'MET_FLOAT'), ('ElementDataFile', []),
         ('Comment', []), ('SeriesDescription', []), ('AcquisitionDate', []),
         ('AcquisitionTime', []),
         ('StudyDate', []), ('StudyTime', [])])

def get_condensed_dim_order(header):
    """Return the condensed dimension order and flip string for this header"""
    if "TransformMatrix" in header and header["TransformMatrix"]:
        transform = header["TransformMatrix"]
        new_dimension_order, flip_orientation = \
            mhd_cosines_to_permutation(
                transform[0:3], transform[3:6], transform[6:9])
    elif "AnatomicalOrientation" in header and header["AnatomicalOrientation"]:
        new_dimension_order, flip_orientation = \
            anatomical_to_permutation(
                header["AnatomicalOrientation"])
    else:
        new_dimension_order = [0, 1, 2]
        flip_orientation = [False, False, False]

    return Axis(new_dimension_order, flip_orientation).to_condensed_format()

def anatomical_to_permutation(anatomical_orientation_string):
    """Dimension permutation vector corresponding to this orientation string"""

    direction_cosine_1 = \
        anatomical_to_cosine(anatomical_orientation_string[0])
    direction_cosine_2 = \
        anatomical_to_cosine(anatomical_orientation_string[1])
    direction_cosine_3 = \
        anatomical_to_cosine(anatomical_orientation_string[2])

    permutation_vector, flip_orientation = \
        mhd_cosines_to_permutation(
            direction_cosine_1, direction_cosine_2, direction_cosine_3)

    return permutation_vector, flip_orientation

def anatomical_to_cosine(anatomical_orientation_char):
    """Get Dicom direction cosine for this orientation string"""
    if anatomical_orientation_char == 'R':
        return [1, 0, 0]
    elif anatomical_orientation_char == 'L':
        return [-1, 0, 0]
    elif anatomical_orientation_char == 'A':
        return [0, 1, 0]
    elif anatomical_orientation_char == 'P':
        return [0, -1, 0]
    elif anatomical_orientation_char == 'I':
        return [0, 0, 1]
    elif anatomical_orientation_char == 'S':
        return [0, 0, -1]

    raise ValueError('No implementation yet for anatomical orientation ' +
                     anatomical_orientation_char + '.')

def permutation_to_cosine(permutation, flip):
    """Get mhd direction cosine for this dimension permutation"""

    dir_cosine = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    dir_cosine[permutation[0]*3] = -1 if flip[0] else 1
    dir_cosine[permutation[1]*3 + 1] = -1 if flip[1] else 1
    dir_cosine[permutation[2]*3 + 2] = -1 if flip[2] else 1

    return dir_cosine

def condensed_to_cosine(condensed_format):
    """Get mhd direction cosine for this condensed format axis"""

    axis = Axis.from_condensed_format(condensed_format)
    return permutation_to_cosine(axis.dim_order, axis.dim_flip)

def mhd_cosines_to_permutation(direction_cosine_1,
                               direction_cosine_2,
                               direction_cosine_3):
    """Get dimension permutation vectors for these mhd direction cosines"""
    orientation_1 = direction_cosine_1
    orientation_2 = direction_cosine_2
    orientation_3 = direction_cosine_3

    permutation_vector, dimension_1, dimension_2, dimension_3 = \
        permutation_from_orientations(orientation_1, orientation_2)

    flip_orientation = get_flip_from_orientations(
        orientation_1, orientation_2, orientation_3, dimension_1, dimension_2,
        dimension_3)
    if np.sum(np.equal(permutation_vector, 0)) != 1 or \
            np.sum(np.equal(permutation_vector, 1)) != 1 or \
            np.sum(np.equal(permutation_vector, 2)) != 1 or \
            np.size(np.setdiff1d(permutation_vector, [0, 1, 2])) != 0:
        raise ValueError('Invalid permutation vector')

    return permutation_vector, flip_orientation

def permutation_from_orientations(orientation_1, orientation_2):
    """Get dimension permutation vectors for these orientation vectors"""
    dimension_1, dimension_2, dimension_3 = \
        dimensions_from_orientations(orientation_1, orientation_2)

    permutation_vector = [2, 2, 2]
    permutation_vector[dimension_1] = 0
    permutation_vector[dimension_2] = 1
    return permutation_vector, dimension_1, dimension_2, dimension_3

def dimensions_from_orientations(orientation_vector_1,
                                 orientation_vector_2):
    """Get dimension permutation vectors for these orientation vectors"""

    dimension_number_1 = np.argmax(np.abs(orientation_vector_1))
    remaining_dimensions = np.setdiff1d([0, 1, 2], dimension_number_1)
    reduced_orientation_vector_2 = np.take(orientation_vector_2,
                                           remaining_dimensions)
    dim2_from_reduced_set = np.argmax(np.abs(reduced_orientation_vector_2))
    dimension_number_2 = remaining_dimensions[dim2_from_reduced_set]
    dimension_number_3 = np.setdiff1d([0, 1, 2],
                                      [dimension_number_1, dimension_number_2])
    dimension_number_3 = dimension_number_3[0]
    return dimension_number_1, dimension_number_2, dimension_number_3

def get_flip_from_orientations(orientation_1, orientation_2, orientation_3,
                               dimension_1, dimension_2, dimension_3):
    """Get dimension flip vectors for these orientation vectors"""

    flip = [False, False, False]
    flip[dimension_1] = orientation_1[dimension_1] < 0
    flip[dimension_2] = orientation_2[dimension_2] < 0
    flip[dimension_3] = orientation_3[dimension_3] < 0
    return flip

def parse_mhd(header):
    """Read a metaheader and returns a FileImageDescriptor"""

    file_format = "mhd"
    dim_order = get_condensed_dim_order(header)
    data_type = DataType.name_from_metaio(header["ElementType"])
    image_size = header["DimSize"]
    msb = header["BinaryDataByteOrderMSB"]
    compression = None
    voxel_size = header['ElementSize']
    return (FileImageDescriptor(file_format=file_format,
                                dim_order=dim_order,
                                data_type=data_type,
                                image_size=image_size,
                                msb=msb,
                                compression=compression,
                                voxel_size=voxel_size), header)


import setuptools

NAME = "smart_sensors_utility"
VERSION = "0.0.2"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools

REQUIRES = [
    "PyMySQL>=0.10.1"
]

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name=NAME,
    version=VERSION,
    author="Paolo Pasquali",
    author_email="paolo.pasquali@outlook.it",
    description="Utility code for Smart Sensors project.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    install_requires=REQUIRES,
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: GNU GPLv3",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)