#t & (t-1) 可以计算二进制数字中1 的个数
class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        result, t = 0, x^y
        while t:
            t = t & (t-1)
            result += 1
        return result
def main():
    sol = Solution()
    result = sol.hammingDistance(1, 4)
    print(result)

if __name__ == "__main__":
    main()


import argparse
import cv2 as cv
import hashlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import os
import readline  # Don't remove !! For prompt of input() to take effect
import sys
import toolz
import urllib.error
import urllib.parse
import urllib.request
import uuid

from mlhub import utils as mlutils
from mlhub.pkg import is_url

# ----------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------

MARK_COLOR = (0, 255, 0)  # Green.  This color remains the same in RGB (matplotlib) and BGR (OpenCV)
MARK_WIDTH = 4
TEXT_COLOR = MARK_COLOR
LINE_WIDTH = 2
TEXT_FONT = cv.FONT_HERSHEY_SIMPLEX
TEXT_SIZE = 1

SERVICE = "Face API"
KEY_FILE = os.path.join(os.getcwd(), "private.txt")

# ----------------------------------------------------------------------
# Command line argument parser
# ----------------------------------------------------------------------

option_parser = argparse.ArgumentParser(add_help=False)

option_parser.add_argument(
    '--key',
    type=str,
    help='Azure face API subscription key')

option_parser.add_argument(
    '--key-file',
    type=str,
    help='file that stores Azure face API subscription key',
    default=KEY_FILE)

# **Note**:
# 1. The endpoint URL varies depending on the region of your service and can be found at Overview page of your service.
#    See 'https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236'
# 1. For Azure face API for Python, endpoint should omit the trailing part of
#    'https://southeastasia.api.cognitive.microsoft.com/face/v1.0'

option_parser.add_argument(
    '--endpoint',
    type=str,
    help='endpoint of Azure face API service')

# ----------------------------------------------------------------------
# File, folder, and I/O
# ----------------------------------------------------------------------

def get_abspath(path):
    """Return the absolute path of <path>.

    Because the working directory of MLHUB model is ~/.mlhub/<model>,
    when user run 'ml score facematch <image-path>', the <image-path> may be a
    path relative to the path where 'ml score facematch' is typed, to cope with
    this scenario, mlhub provides mlhub.utils.get_cmd_cwd() to obtain this path.
    """

    path = os.path.expanduser(path)
    if not os.path.isabs(path):
        path = os.path.join(mlutils.get_cmd_cwd(), path)

    return os.path.abspath(path)

def list_files(path, depth=0):
    """List all files in <path> at level <depth>.  If depth < 0, list all files under <path>."""

    path = os.path.join(path, '')
    start = len(path)
    for (root, dirs, files) in os.walk(path):
        if depth < 0:
            for file in files:
                yield os.path.join(root, file)
        else:
            segs = root[start:].split(os.path.sep)
            if (depth == 0 and segs[0] == '') or len(segs) == depth:
                for file in files:
                    yield os.path.join(root, file)

def download_img(url, folder, prefix):
    """Download image from <url> into <folder> with name as <prefix>_<md5>."""

    # Download image from <url> into a unique file path with <prefix>

    path = os.path.join(folder, get_unique_name(prefix))
    urllib.request.urlretrieve(url, path)

    return replace_uuid_with_digest(path)

def get_hexdigest(path):
    with open(path, 'rb') as file:
        digest = hashlib.md5(file.read()).hexdigest()

    return digest

def get_unique_name(prefix):
    """Return a unique name as prefix_uuid."""

    prefix = '_'.join(prefix.split()) if prefix is not None else 'temp'
    number = str(uuid.uuid4().hex)
    return prefix + '_' + number

def change_name_hash(name, digest):
    """Change name from prefix_uuid to prefix_digest."""

    name = name.split('_')
    name[-1] = digest
    return '_'.join(name)

def get_name_hash(name):
    return name.split('_')[-1]

def replace_uuid_with_digest(path):
    """Replace uuid in path name with md5 digest"""

    digest = get_hexdigest(path)
    new_path = change_name_hash(path, digest)
    os.rename(path, new_path)
    return new_path, digest

def make_name_dir(path, name):
    """Createa dir under <path> for person <name> where <name> may contain spaces."""

    name_dir = '_'.join(name.split())
    name_dir_path = os.path.join(path, name_dir)
    os.makedirs(name_dir_path, exist_ok=True)
    return name_dir_path

def stop(msg, status=0):
    print(msg, file=sys.stderr)
    sys.exit(status)

# ----------------------------------------------------------------------
# Image
# ----------------------------------------------------------------------

def read_cv_image_from(url):
    """Read an image from url or file as grayscale opencv image.

    **Note**: OpenCV return the image as numpy array, which can also directly
    be used by other Python image libraries.  However, the color space in
    OpenCV is BGR instead of the popular RGB.
    """

    return toolz.pipe(
        url,
        urllib.request.urlopen if is_url(url) else lambda x: open(x, 'rb'),
        lambda x: x.read(),
        bytearray,
        lambda x: np.asarray(x, dtype="uint8"),
        lambda x: cv.imdecode(x, cv.IMREAD_COLOR))

def convert_cv2matplot(*images):
    """Convert color space between OpenCV and Matplotlib.

    Because OpenCV and Matplotlib use different color spaces.
    """

    if len(images) > 0:
        res = []
        for image in images:
            image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
            res.append(image)

        return res[0] if len(res) == 1 else tuple(res)
    else:
        return None

def _plot_image(ax, img, cmap=None, label='', text=None):
    """Plot <img> in <ax>."""

    ax.imshow(img, cmap)
    ax.tick_params(
        axis='both',
        which='both',
        # bottom='off',  # 'off', 'on' is deprecated in matplotlib > 2.2
        bottom=False,
        # top='off',
        top=False,
        # left='off',
        left=False,
        # right='off',
        right=False,
        # labelleft='off',
        labelleft=False,
        # labelbottom='off')
        labelbottom=False)
    ax.set_xlabel(label)
    if text:
        ax.text(0, -10, text)

def plot_side_by_side_comparison(
        leftimg,
        rightimg,
        leftlabel='Original Image',
        rightlabel='Result',
        leftcmap=None,
        rightcmap=None,
        leftdescription=None,
        rightdescription=None):
    """Plot two images side by side."""

    # Setup canvas

    plt.rcParams.update({'figure.autolayout': True})
    gs = gridspec.GridSpec(6, 13)
    gs.update(hspace=0.1, wspace=0.001)
    fig = plt.figure(figsize=(7, 3))

    # Plot Left image

    ax = fig.add_subplot(gs[:, 0:6])
    _plot_image(ax, leftimg, cmap=leftcmap, label=leftlabel, text=leftdescription)

    # Plot right image

    ax = fig.add_subplot(gs[:, 7:13])
    _plot_image(ax, rightimg, cmap=rightcmap, label=rightlabel, text=rightdescription)

    # Show all of them

    plt.show()

def show_image(url, show=True):
    """Read image from <url> and display."""

    img = read_cv_image_from(url)
    img = convert_cv2matplot(img)
    if show:
        display(img)
    return img

def display(img, frombgr=False, text=None):
    """Display <img> array."""

    if frombgr:
        img = convert_cv2matplot(img)
    height, _, _ = img.shape
    plt.rcParams.update({'figure.autolayout': True})
    plt.axis('off')

    if text:
        lines = text.split('\n')
        for i, line in enumerate(lines):
            plt.text(0, height + 30*(i+1), line)

    plt.imshow(img)
    plt.show()

# ----------------------------------------------------------------------
# Face
# ----------------------------------------------------------------------

def get_face_api_key_endpoint(subscription_key, endpoint):
    endpoint = '/'.join(endpoint.split('/')[:3])  # Remove any trailing path
    return subscription_key, endpoint

def getbox(face):
    """Convert width and height in face to a point in a rectangle"""

    rect = face.face_rectangle
    left = rect.left
    top = rect.top
    right = left + rect.width
    bottom = top + rect.height
    return top, right, bottom, left

def getbox_points(face):
    top, right, bottom, left = getbox(face)
    return left, top, left, bottom, right, bottom, right, top

def mark_face(image, face, text=None):
    """Mark the <faces> in <image>.

    Args:
        image: An OpenCV BGR image.
        face: A face cooridinate tuple (top, right, bottom, left).
        text: Text would be displayed above the face box.
    """

    # Draw a rectangle around the faces

    (textwidth, textheight), baseline = cv.getTextSize(text, TEXT_FONT, TEXT_SIZE, LINE_WIDTH)
    top, right, bottom, left = face
    cv.rectangle(image, (left, top), (right, bottom), MARK_COLOR, MARK_WIDTH)

    if text:
        imgheight, imgwidth, _ = image.shape

        y = top - baseline
        if y < textheight:
            y = bottom + textheight
            if y + baseline > imgheight:
                y = top + textheight

        x = int(left + (right - left - textwidth)/2)
        if x < 0:
            x = 0
        elif x + textwidth > imgwidth:
            x = imgwidth - textwidth

        cv.putText(image, text, (x, y), TEXT_FONT, TEXT_SIZE, TEXT_COLOR, LINE_WIDTH)

def interpret_glasses(glasses):
    return glasses if glasses != 'noGlasses' else "no glasses"

def interpret_emotion(emotion):
    return max(vars(emotion), key=lambda attr: getattr(emotion, attr) if getattr(emotion, attr) else 0)

def interpret_occlusion(occlusion):
    res = []
    for k, v in vars(occlusion).items():
        if v:
            res.append(k)
    if res:
        return ', '.join(res)
    else:
        return "no occlusion"

def show_detection_results(img_url, faces):
    bgr = read_cv_image_from(img_url)
    description = ''
    if faces:
        labels = {face.face_id: str(i) for i, face in enumerate(faces)}
        for face in faces:
            mark_face(bgr, getbox(face), text=labels[face.face_id])
            attrs = face.face_attributes
            description += "Face No. {}: {} years-old, {}, {}, {}, {}\n".format(
                labels[face.face_id],
                attrs.age,
                attrs.gender,
                interpret_glasses(attrs.glasses),
                interpret_emotion(attrs.emotion),
                interpret_occlusion(attrs.occlusion))
    else:
        print("    No faces found!", file=sys.stderr)

    # Display the image in the users default image browser.

    display(bgr, frombgr=True, text=description)

def print_detection_results(faces):
    if faces:
        for face in faces:
            coordinates = " ".join([str(x) for x in getbox_points(face)])
            attrs = face.face_attributes
            description = "{},{},{},{},{},{}".format(
                coordinates,
                attrs.age,
                attrs.gender,
                interpret_glasses(attrs.glasses),
                interpret_emotion(attrs.emotion),
                interpret_occlusion(attrs.occlusion))
            print(description)

def azface_detect(client, img_url, **kwargs):
    """Detect faces using Azure face API."""

    if is_url(img_url):  # Photo from URL
        # For return_face_attributes, it can be a FaceAttributeType, or a list of string
        faces = client.face.detect_with_url(img_url, **kwargs)
    else:  # Photo from a file
        with open(img_url, 'rb') as file:
            # For face attributes, it can be a FaceAttributeType, or a list of string
            faces = client.face.detect_with_stream(file, **kwargs)

    return faces

def azface_similar(client, target_faces, candidate_faces):
    matches = {}
    if candidate_faces:
        candidate_ids = [x.face_id for x in candidate_faces]

        for query_face in target_faces:

            # Call Azure face API to find matches

            similar_faces = client.face.find_similar(query_face.face_id, face_ids=candidate_ids)

            # Update the best matched face

            if similar_faces:
                best_match = max(similar_faces, key=lambda face: face.confidence)
                match_face = next(x for x in candidate_faces if x.face_id == best_match.face_id)
                if match_face.face_id not in matches or matches[match_face.face_id][1] < best_match.confidence:
                    matches[match_face.face_id] = (query_face, best_match.confidence)

    return matches

def show_similar_results(target_url, target_faces, candidate_url, candidate_faces, matches):
    if candidate_faces:
        labels = {face.face_id: str(i) for i, face in enumerate(target_faces)}

        # Mark matched faces

        target_bgr = read_cv_image_from(target_url)
        candidate_bgr = read_cv_image_from(candidate_url)

        for face in target_faces:
            mark_face(target_bgr, getbox(face), text=labels[face.face_id])

        description = []
        for face in candidate_faces:
            if face.face_id in matches:
                number = labels[matches[face.face_id][0].face_id]
                mark_face(candidate_bgr, getbox(face), text=number)
                description.append("Face No. {}: {}".format(number, matches[face.face_id][1]))
            else:
                mark_face(candidate_bgr, getbox(face), text='?')

        # Plot results

        print("\nPlease close each image window (Ctrl-w) to proceed.", file=sys.stderr)
        plot_side_by_side_comparison(
            *convert_cv2matplot(target_bgr, candidate_bgr),
            leftlabel='Target faces',
            rightlabel='Matched faces',
            rightdescription=None if not description else "Matching confidence:\n{}".format('\n'.join(description)))

    else:
        print("No faces found in {}".format(candidate_url), file=sys.stderr)

def print_similar_results(target_faces, candidate_faces, matches):
    target_ids = {face.face_id: face for face in target_faces}
    candidate_ids = {face.face_id: face for face in candidate_faces}

    # matched faces

    if matches:
        for face in candidate_faces:
            if face.face_id in matches:
                target_face, confidence = matches[face.face_id]
                del target_ids[target_face.face_id]
                del candidate_ids[face.face_id]
                target_coordinates = " ".join([str(x) for x in getbox_points(target_face)])
                match_coordinates = " ".join([str(x) for x in getbox_points(face)])
                description = "{},{},{}".format(
                    target_coordinates,
                    match_coordinates,
                    confidence)
                print(description)

    # unmatched faces

    for face in target_ids.values():
        target_coordinates = " ".join([str(x) for x in getbox_points(face)])
        description = "{},,".format(target_coordinates)
        print(description)

    for face in candidate_ids.values():
        match_coordinates = " ".join([str(x) for x in getbox_points(face)])
        description = ",{},".format(match_coordinates)
        print(description)

def azface_add(client, img_url, name, person=None):
    """Add the face in img_url to the person name."""

    display(read_cv_image_from(img_url), frombgr=True)

    # Use the person name as person group ID and person group name

    person_group_id = name
    person_group_name = name
    person_name = name

    if not person:  # Get the person information.  Create it if not available

        # Get the list of person groups

        person_groups = client.person_group.list()
        person_groups = [x.person_group_id for x in person_groups]

        # Get the list of persons in the person group

        person_list = client.person_group_person.list(person_group_id)

        # Create a person group if not available

        if person_group_id not in person_groups:
            client.person_group.create(person_group_id, name=person_group_name)

        # Create a person belongs to the person group if not available

        try:
            person = next(x for x in person_list if x.name == person_name)
        except StopIteration:
            person = client.person_group_person.create(person_group_id, name=person_name)

    # Add face for the person

    if is_url(img_url):  # Photo from URL
        client.person_group_person.add_face_from_url(person_group_id, person.person_id, img_url)
    else:  # Photo from a file
        with open(img_url, 'rb') as file:
            client.person_group_person.add_face_from_url(person_group_id, person.person_id, file)

    return person


import heapq
import sys

n = int(sys.stdin.readline())

left = []
right = []

for i in range(n):
    num = int(sys.stdin.readline())

    if len(left) == len(right): #leftheap에 넣기
        heapq.heappush(left, -num)
    else: #rightheap에 넣기
        heapq.heappush(right, num)

    if right and right[0] < -left[0]: #right에 작은 값이 들어갈 경우 교환
        left_val = heapq.heappop(left)
        right_val = heapq.heappop(right)

        heapq.heappush(left -right_val)
        heapq.heappush(right, -left_val)

    print(-left[0])


def original(n,data):
    a=[]
    for i in data:
        if i not in a:
            a.append(i)
    return a
n=int(input())
c=0
data=list(map(int,input().split()))
d=original(n,data)
print(*d)

for i in range(len(d)):
    if data[i]==d[i]:
        c+=1
print(c)
"""
10
4 3 1 2 5 3 2 6 7 6
output:
4 3 1 2 5 6 7
"""


# -*- coding: utf-8 -*-
import jieba
from gensim import corpora, models
from jieba import analyse
import math
import jieba.posseg as psg
import functools
import time
from sklearn.linear_model import SGDClassifier
import joblib
from langconv import *

# 繁体转简体
def TraditionalToSimplified(content):
    line = Converter("zh-hans").convert(content)
    return line

# 停用词表加载方法
def get_stopword_list():
    # 停用词表存储路径，每一行为一个词，按行读取进行加载
    # 进行编码转换确保匹配准确率
    stop_word_path = './data/stopword.txt'
    stopword_list = [sw.replace('\n', '') for sw in open(stop_word_path,encoding='utf-8').readlines()]
    return stopword_list

# 分词方法，调用结巴接口
def seg_to_list(sentence, pos=False):
    if not pos:
        # 不进行词性标注的分词方法
        # sentence = sentence.strip()
        # seg_list = sentence.split()
        sentence = TraditionalToSimplified(sentence)
        seg_list = sentence.strip().replace(';',' ').split()
    else:
        # 进行词性标注的分词方法
        seg_list = psg.cut(sentence)
    return seg_list

# 去除干扰词
def word_filter(seg_list, pos=False):
    stopword_list = get_stopword_list()
    filter_list = []
    # 根据POS参数选择是否词性过滤
    ## 不进行词性过滤，则将词性都标记为n，表示全部保留
    for seg in seg_list:
        if not pos:
            word = seg
            flag = 'n'
        else:
            word = seg.word
            flag = seg.flag
        if not flag.startswith('n'):
            continue
        # 过滤停用词表中的词，以及长度为<2的词(这里小于2的条件我去掉了，大家可以根据需求增加)
        if not word in stopword_list:
            filter_list.append(word)

    return filter_list

# 数据加载，pos为是否词性标注的参数，corpus_path为数据集路径
def load_data(pos=False, corpus_path='./data/train_src.txt'):
    # 调用上面方式对数据集进行处理，处理后的每条数据仅保留非干扰词
    doc_list = []
    inputs = open(corpus_path, 'r', encoding='utf-8')
    for line in inputs:
        seg_list = seg_to_list(line, pos)
        filter_list = word_filter(seg_list, pos)
        doc_list.append(filter_list)
    inputs.close()
    return doc_list

# idf值统计方法
def train_idf(doc_list):
    idf_dic = {}
    # 总文档数
    tt_count = len(doc_list)

    # 每个词出现的文档数
    for doc in doc_list:
        for word in set(doc):
            idf_dic[word] = idf_dic.get(word, 0.0) + 1.0

    # 按公式转换为idf值，分母加1进行平滑处理
    for k, v in idf_dic.items():
        idf_dic[k] = math.log(tt_count / (1.0 + v))

    # 对于没有在字典中的词，默认其仅在一个文档出现，得到默认idf值
    default_idf = math.log(tt_count / (1.0))
    return idf_dic, default_idf

import numpy as np
#  排序函数，用于topK关键词的按值排序
def cmp(e1, e2):
    res = np.sign(e1[1] - e2[1])
    if res != 0:
        return res
    else:
        a = e1[0] + e2[0]
        b = e2[0] + e1[0]
        if a > b:
            return 1
        elif a == b:
            return 0
        else:
            return -1

# TF-IDF类
class TfIdf(object):
    # 四个参数分别是：训练好的idf字典，默认idf值，处理后的待提取文本，关键词数量
    def __init__(self, idf_dic, default_idf, word_list, keyword_num):
        self.word_list = word_list
        self.idf_dic, self.default_idf = idf_dic, default_idf
        self.tf_dic = self.get_tf_dic()
        self.keyword_num = keyword_num

    # 统计tf值
    def get_tf_dic(self):
        tf_dic = {}
        for word in self.word_list:
            tf_dic[word] = tf_dic.get(word, 0.0) + 1.0

        tt_count = len(self.word_list)
        for k, v in tf_dic.items():
            tf_dic[k] = float(v) / tt_count

        return tf_dic

    # 按公式计算tf-idf
    def get_tfidf(self):
        tfidf_dic = {}
        for word in self.word_list:
            idf = self.idf_dic.get(word, self.default_idf)
            tf = self.tf_dic.get(word, 0)

            tfidf = tf * idf
            tfidf_dic[word] = tfidf

        return self.tf_dic , tfidf_dic

def tfidf_extract(word_list, pos=False, train=True, keyword_num=3):
    if train:
        idf_dic, default_idf = train_idf(doc_list_train_src)
    else:
        idf_dic, default_idf = train_idf(doc_list_test_src)
    tfidf_model = TfIdf(idf_dic, default_idf, word_list, keyword_num)
    tf_list , tfidf_list = tfidf_model.get_tfidf()
    return tf_list , tfidf_list

def keyword_list(keypath='./data/test_trg.txt'):
    inputs = open(keypath, 'r', encoding='utf-8')
    keyword_list =[]
    for line in inputs:
        line = TraditionalToSimplified(line)
        keyword_list.append(line.strip().replace(';',' ').split())
    inputs.close()
    return keyword_list

def get_first_three_keywords(keywordslist, row=1):
    length = len(keywordslist[row - 1])
    first_word = keywordslist[row - 1][0]
    m = min(length, 3)
    first_three_keywords = set(keywordslist[row - 1][:m])
    return first_word, first_three_keywords

def get_feature_label(readpath='./data/train_src.txt' ,
                      keypath='./data/train_trg.txt',train=True, end =1):
    if train:
        line_length = len(doc_list_train_src)
        doc_list = doc_list_train_src
    else:
        line_length = len(doc_list_test_src)
        doc_list = doc_list_test_src
    keywords = keyword_list(keypath)
    features = []
    target = []
    word = []
    for n in range(line_length):
        print(str(n+1))
        tf_list, tfidf_list = tfidf_extract(doc_list[n], train=train)
        p = 1
        for k, v in tf_list.items():
            temp = []
            if k in keywords[n]:
                target.append(1)
            else:
                target.append(0)
            temp.append(v)
            temp.append(tfidf_list.get(k, 0))
            temp.append(p)
            p = p + 1
            features.append(temp)
        word.append(list(tf_list.keys()))
        if (n+1) == end:
            break
    features = np.array(features)
    labels = np.array(target)
    return features , labels , word

def SGD(classifier, train_features, train_labels,
        test_word ,test_features, test_labels,
        load=True, save=True,
        savepath='./result/sgd.txt', end =1):
    #是否训练保存模型
    if not load:
        classifier.fit(train_features , train_labels) #训练模型
        print("model start to save")
        joblib.dump(classifier, 'saved_model/sgd_default.pkl')
        print("model save successfully")

    print("model start to load")
    classifier = joblib.load('saved_model/sgd.pkl') # 加载训练好的分类器
    print("model load successfully")

    line_length = len(doc_list_test_src) # 测试集总行数
    c = 0 # 每句的开始序号
    f1_1 = 0 # f1@1指标
    f1_3 = 0 # f1@3指标
    sum_ap = 0 #所有平均精确度的和，也就是每句话的平均精度之和
    keywordslist = keyword_list() #关键词列表
    string = ''
    for n in range(line_length):
        length = len(test_word[n])
        if length == 0:
            continue
        pred_proba = classifier.predict_proba(test_features[c:(c + length)])
        l = []
        for i in range(min(5,length)):
            t = []
            t.append(test_word[n][i])
            t.append(pred_proba[i][1])
            t.append(test_labels[c+i])
            l.append(t)
        c = c + length
        l.sort(key=functools.cmp_to_key(cmp), reverse=True)
        sum_p = 0 #每句话的精确率之和
        sum = 0 #top-i的True positive值
        for i in range(len(l)):
            # 计算每句话的精度之和
            sum = sum + l[i][2]
            sum_p = sum_p + sum / (i + 1)
        sum_ap = sum_ap + sum_p / len(l)
        first_keyword_pred = l[0][0]
        first_three_keywords_pred = set()
        for k, v, p in l[:min(3,length)]:
            first_three_keywords_pred.add(k)
        first_keyword , first_three_keywords = get_first_three_keywords(keywordslist, n+1)
        str1 = str(n+1) + '\t' + first_keyword_pred \
               + '\t' + '\t' + '\t' + first_keyword
        str2 = str(n+1) + '\t' + str(first_three_keywords_pred) \
               + '\t' + '\t' + str(first_three_keywords)
        string = string + str1 + str2
        # print(str1)
        # print(str2)
        if first_keyword_pred == first_keyword:
            f1_1 = f1_1 + 1
        if len(first_three_keywords_pred & first_three_keywords) == len(first_three_keywords):
            f1_3 = f1_3 + 1
        if (n+1) == end:
            break
    print('SGD-tfidf model result :')
    print("F1@1 : " + str(f1_1 / line_length * 100) + "%")
    print("F1@3 : " + str(f1_3 / line_length * 100) + "%")
    print("mAP : " + str(sum_ap / line_length * 100) + "%")
    if save: #是否保存结果
        outputs = open(savepath, 'w', encoding='utf-8')
        outputs.write('行数' + '\t' + '预测值' + '\t' + '\t' + '\t' + '真实值' + '\n')
        outputs.write(string)
        outputs.write("F1@1 : " + str(f1_1 / line_length * 100) + "%" + '\n')
        outputs.write("F1@3 : " + str(f1_3 / line_length * 100) + "%" + '\n')
        outputs.write("mAP : " + str(sum_ap / line_length * 100) + "%")
        outputs.close()
        print("result save successfully")

def main():
    # # 验证集特征提取
    # valid_features, valid_labels , valid_word = get_feature_label(readpath='./data/valid_src.txt',
    #                                                savepath='./data/valid_trg.txt', end=1)
    # train_features, train_labels, train_word = get_feature_label(end=0) # 训练集特征提取
    # test_features, test_labels, test_word = get_feature_label(readpath='./data/test_src.txt',
    #                                                           keypath='./data/test_trg.txt',
    #                                                           train=False, end=0) # 测试集特征提取
    #
    # print("Numpy start to save")
    # np.savez('./data/dataset_own.npz', train_features, train_labels, test_word,
    #          test_features, test_labels, allow_pickle=True, fix_imports=True) # 保存特征为numpy矩阵
    # print("Numpy save successfully")

    print("Numpy start to load")
    npzfile = np.load('./data/dataset.npz', allow_pickle=True, fix_imports=True) # 加载特征numpy矩阵
    print("Numpy load successfully")

    #创建SGD分类器模型
    sgd = SGDClassifier(loss='log', random_state=66) #随机数66
    SGD(classifier=sgd, # 分类器
        train_features=npzfile['arr_0'], # 训练集特征矩阵形式
        train_labels=npzfile['arr_1'], # 训练集标签
        test_word=npzfile['arr_2'], # 测试集词列表，主要用于结果输出
        test_features=npzfile['arr_3'], #测试集特征矩阵形式
        test_labels=npzfile['arr_4'], #测试集标签矩阵形式
        load=True, #是否加载训练好的模型，否的话先训练并保存然后加载模型测试
        save=True, #是否保存结果
        savepath='./result/sgd.txt', #SGD结果保存路径
        end=0) #运行至第几行，设置0时为全部

if __name__ == '__main__':
    print(time.strftime('Strat to prepare:%H:%M:%S', time.localtime(time.time())))
    # 预处理加载好训练集和关键词
    doc_list_train_src = load_data(corpus_path='data/train_src.txt')
    doc_list_test_src = load_data(corpus_path='data/test_src.txt')
    print(time.strftime('Preparations have been done:%H:%M:%S', time.localtime(time.time())))
    main()
    print(time.strftime('End time:%H:%M:%S', time.localtime(time.time())))


import cv2
import numpy as np

img = cv2.imread("lena.png")
print(img.shape)

#HUE
B=img[:,:,0]
G=img[:,:,1]
R =img[:,:,2]
t = 0.5*((R - G) + (R - B))
m = np.sqrt((R - G)**2.0 + (R - B)*(G - B))
theta = np.arccos(t/m)
print(theta)
theta = (180/np.pi)*theta
print(theta)
theta = theta.astype(np.uint8)
filt1 = B>G
filt2 = B<=G
H = filt1*(360-theta) + filt2*theta
H=H.astype(np.uint8)

#SATURATION
S = 1 - 3/np.sum(img,axis=-1) * np.min(img,axis =-1)
S = S*255
S = S.astype(np.uint8)

#INTENSITY
I =  np.sum(img,axis=2)/3
I = I.astype(np.uint8)
print(I)

#HSI
HSI = img.copy()
HSI[:,:,0]=I
HSI[:,:,1]=S
HSI[:,:,2]=H

cv2.imshow('Anh mau goc Lena', img)
cv2.imshow('kenh H Lena', H)
cv2.imshow('kenh S Lena', S)
cv2.imshow('kenh I Lena', I)
cv2.imshow('Anh HSI Lena', HSI.astype(np.uint8))
cv2.waitKey(0)


# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 09:01:49 2021

@author: these
"""

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 15:25:21 2021

@author: these
"""
import pandas as pd
import numpy as np
import re
knock_out_dates=['2021-06-25','2021-07-26','2021-08-25','2021-09-27','2021-10-25','2021-11-25','2021-12-27','2022-01-25','2022-02-25','2022-03-25']
Spast=pd.DataFrame([100],index=['2021-03-25'])
snow1=snowball_basic(name='testNo1',startdate='2021-03-25',enddate='2022-03-25',\
                     curdate='2021-03-25',underlying='000905.SH',Spast=Spast,\
                     r=0.04,b=0.04,knock_out_ratio=1.03,knock_in_ratio=0,knock_in_option_payoff=nothing_payoff,\
                     knock_out_dates=knock_out_dates,\
                     knock_out_payoff_yearly_rates=0.1,\
                     nothing_happens_payoff_yearly_rates=0.03)

temp=snow1.pricing_snowball_basic_MC(snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.3,\
                           snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\
                           snow1.b,snow1.knock_out_dates,1.05,\
                           0.05,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\
                           -0.05,S_sim_class=S_sim_BS,T_year_S_sim=snow1.T_year_S_sim,\
                           date_series_funcs=tday_interval,date_noofdays_funcs=tday_noofdays,\
                           date_series_gen_args={},S_gen_args={'freq':1,'MC_M':1000},tag3='')
temp['pricing']
np.mean(temp['pricing_detail'])
np.std(temp['pricing_detail'])/np.mean(temp['pricing_detail'])

payoff_func,Spast,K,startdate,enddate,curdate,r,b,sigma,\
                           T_year_interest,T_day_interest_noofdays_func,\
                           mu,knock_out_dates,knock_out_ratio,\
                           knock_out_payoff_yearly_rates,knock_in_ratio,knock_in_option_payoff,\
                           nothing_happens_payoff_yearly_rates,S_sim_class=\
                           snow1.payoff_func,Spast,snow1.K,snow1.startdate,snow1.enddate,snow1.curdate,snow1.r,snow1.b,0.3,\
                           snow1.T_year_interest,snow1.T_day_interest_noofdays_func,\
                           snow1.b,snow1.knock_out_dates,1.05,\
                           0.05,snow1.knock_in_ratio,snow1.knock_in_option_payoff,\
                           -0.05,S_sim_BS
T_year_S_sim=snow1.T_year_S_sim
date_series_funcs=tday_interval
date_noofdays_funcs=tday_noofdays
date_series_gen_args={}
S_gen_args={'freq':1,'MC_M':1000}
tag3=''

测试案例_保本雪球.py

测试案例_保本雪球.py


from sys import exit #exists program without raising error if input is not as expected

#! function is created
def gold_room():
    print("This room is full of gold. How much do you take?") #print message
    print("options: 0 or 1... maybe more?")
    choice = input("> ") #takes input from user

    if "0" in choice or "1" in choice: #if input is 0 or 1:
        how_much = int(choice) # the input is stored in variable how_much and converted to an int
    else: #if user does't type a valid format int, the next line will be printed
        dead("Man, learn to type a number!") #function call
    if how_much < 50: #if user's input is < 50 the next line will be printed
        print("Nice, you're not greedy, you win!")
        exit(0) #exits program without errors
    else: #if user chooses a value >50 the next line is executed
        dead("You greedy bastards!")

#! function is declared
def bear_room():
    print("There is a bear here.") #prints message
    print("The bear has a bunch of honey.") #prints message
    print("The fat bear is in front of another door") #prints message
    print("How are you going to move the bear?") #prints message
    print("options: take honey - taunt bear - open door") #prints message
    bear_moved = False #creates variable = to False

    while True: #while statement
        choice = input("> ") # takes input from user

        if choice == "take honey": #if user chooses 'take hone'. the function dead() will be called and the message will be stored in the why parameter in dead()
            dead("The bear looks at you then slaps your face off!")
        elif choice == "taunt bear" and not bear_moved: #if user chooses "taunt bear", the statement not bear_moved is = True
            print("The bear has moved from the door.")
            print("You can go through it now.")
            print("option: 'open door' or 'taunt bear'")
            bear_moved = True #variable is changed from False to True
        elif choice == "taunt bear" and bear_moved: #if user chooses "taunt bear" again the variable bear_moved would be False and the function dead() will be executed
            dead("The bear gets pissed off and chews your leg off :)") #function is called and executed, message is stored as parameter
        elif choice == "open door" and bear_moved: #if user chooses "open door", the function gold_
            gold_room() #call to gold_room function
        else: #else statement if user input is a not-defined option
            print("I got no idea what that means :(") #prints message

#! function definition
def cthulhu_room():
    print("Here you see the great evil Cthulhu") #prints message
    print("He, it, whatever stares at you and you go insane!") #prints message
    print("Do you flee for your life or eat your head?") #prints message
    print("options: Flee or head") #prints message

    choice = input("> ") #takes input from user

    if "flee" in choice: #if statement, if user inputs 'flee' in previous choice = input, it will take him to start function
        start() #function call to start function
    elif "head" in choice: #if user chooses "head" the function dead() will be called, it will take the message as parameter
        dead("well that was nasty!")
    else: #if user inputs any other message, the cthulhu_room() will be called again until user chooses one of the previous options
        cthulhu_room()

#! function definition
def dead(why): #function takes one parameter (why) which acts as placeholder for later given values.
    print(why, "good job!!!") # takes parameter and prints message
    print("you're De4ad :(") #prints message
    print("Play again any other time!") #prints message

#! function definition:
def start():
    print("You are in a dark room.") #prints message
    print("There is a door to your right and left.") #prints message
    print("which one do you take?") #prints message
    print("options: left or right") #prints message

    choice = input("> ") #takes input from user

    if choice == "left": #if user chooses left, it take him to the function bear_room()
        bear_room()
    elif choice == "right": #if user chooses right it will take him to the function cthulhu_room()
        cthulhu_room()
    else: #if user inputs something else beside left or right it will display message:
        dead("You stumble around the room until you starve")

start()#call of function


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from .models import Group, GroupInvitation, GroupMessage
from .serializers import GroupSerializer, GroupMessageSerializer, GroupInvitationSerializer
from users.models import CustomUser

# Create new group

class CreateGroupView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        # Get group name and recipients from the request data
        group_name = request.data.get("group_name")
        recipient_ids = request.data.get(
            "recipient_ids", [])  # List of user IDs to invite

        # Validate if group name exists
        if not group_name:
            return Response({"error": "Group name required"}, status=status.HTTP_400_BAD_REQUEST)

        # Validate recipient_ids to ensure it's provided as a list
        if not recipient_ids or not isinstance(recipient_ids, list):
            return Response({"error": "Recipient IDs must be provided as a list"}, status=status.HTTP_400_BAD_REQUEST)

        # Create the group and add the authenticated user as a member
        group = Group.objects.create(name=group_name)
        group.members.add(request.user)

        # Gather all the recipients from provided recipient_ids
        recipients = []
        for r_id in recipient_ids:
            try:
                recipient = CustomUser.objects.get(pk=r_id)
                recipients.append(recipient)
            except CustomUser.DoesNotExist:
                group.delete()  # Delete the group if an invalid recipient is found
                return Response({"error": f"Recipient with ID {r_id} not found"}, status=status.HTTP_404_NOT_FOUND)

        # Send group invitations to all recipients
        for recipient in recipients:
            if not GroupInvitation.objects.filter(sender=request.user, recipient=recipient, group=group).exists():
                GroupInvitation.objects.create(
                    sender=request.user, recipient=recipient, group=group)

        return Response({"message": "Group created and invitations sent successfully", "group_id": group.id}, status=status.HTTP_201_CREATED)

# Send group invitation

class SendGroupInvitationView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        # Get group ID and recipient IDs from the request data
        recipient_ids = request.data.get('recipient_ids', [])
        group_id = request.data.get('group_id')

        # Validate recipient_ids and group_id
        if not recipient_ids or not isinstance(recipient_ids, list):
            return Response({"error": "Recipient IDs must be provided as a list"}, status=status.HTTP_400_BAD_REQUEST)
        if not group_id:
            return Response({"error": "Group ID is required"}, status=status.HTTP_400_BAD_REQUEST)

        # Check if the group exists
        try:
            group = Group.objects.get(pk=group_id)
        except Group.DoesNotExist:
            return Response({"error": "Group not found"}, status=status.HTTP_404_NOT_FOUND)

        # Gather all the recipients
        recipients = []
        for r_id in recipient_ids:
            try:
                recipient = CustomUser.objects.get(pk=r_id)
                recipients.append(recipient)
            except CustomUser.DoesNotExist:
                return Response({"error": f"Recipient with ID {r_id} not found"}, status=status.HTTP_404_NOT_FOUND)

        # Send group invitations to all recipients
        for recipient in recipients:
            if not GroupInvitation.objects.filter(sender=request.user, recipient=recipient, group=group).exists():
                GroupInvitation.objects.create(
                    sender=request.user, recipient=recipient, group=group)

        return Response({"message": "Invitations sent successfully"}, status=status.HTTP_201_CREATED)

# Accept group invitation

class AcceptGroupInvitationView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        # Get the invitation ID from the request data
        invitation_id = request.data.get('invitation_id')

        if not invitation_id:
            return Response({"error": "Invitation ID is required"}, status=status.HTTP_400_BAD_REQUEST)

        # Check if the invitation exists and hasn't been accepted yet
        try:
            invitation = GroupInvitation.objects.get(
                pk=invitation_id, recipient=request.user, accepted=False)
        except GroupInvitation.DoesNotExist:
            return Response({"error": "Invitation not found or already accepted"}, status=status.HTTP_404_NOT_FOUND)

        # Mark the invitation as accepted and add the user to the group members
        invitation.accepted = True
        invitation.save()
        invitation.group.members.add(request.user)

        return Response({"message": "Invitation accepted successfully"}, status=status.HTTP_201_CREATED)

# Send group message

class SendGroupMessageView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        # Get group ID and message content from the request data
        group_id = request.data.get('group_id')
        content = request.data.get('content')

        # Validate the provided data
        if not group_id or not content:
            return Response({"error": "Group and content are required"}, status=status.HTTP_400_BAD_REQUEST)

        # Check if the group exists
        try:
            group = Group.objects.get(pk=group_id)
        except Group.DoesNotExist:
            return Response({"error": "Group not found"}, status=status.HTTP_404_NOT_FOUND)

        # Ensure that the authenticated user is a member of the group
        if request.user not in group.members.all():
            return Response({"error": "User not a member of the group"}, status=status.HTTP_403_FORBIDDEN)

        # Create the group message
        GroupMessage.objects.create(
            sender=request.user, group=group, content=content)

        return Response({"message": "Message sent successfully"}, status=status.HTTP_201_CREATED)

# List al group invitations

class ListGroupInvitationsView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        # Get all unaccepted group invitations for the authenticated user
        invitations = GroupInvitation.objects.filter(
            recipient=request.user, accepted=False)
        serializer = GroupInvitationSerializer(invitations, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

# List all group messages

class ListGroupMessagesView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, group_id):
        # Check if the group exists and the user is a member
        try:
            group = Group.objects.get(pk=group_id)
            if request.user not in group.members.all():
                return Response({"error": "User not a member of the group"}, status=status.HTTP_403_FORBIDDEN)

            # Get all messages for the given group
            messages = GroupMessage.objects.filter(group=group)
            serializer = GroupMessageSerializer(messages, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except Group.DoesNotExist:
            return Response({"error": "Group not found"}, status=status.HTTP_404_NOT_FOUND)

# List all groups the user is a member of

class ListGroupsView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        # Filter groups where the user is a member
        groups = Group.objects.filter(members=request.user)
        serializer = GroupSerializer(groups, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

# Decline group invitation

class DeclineGroupInvitationView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        invitation_id = request.data.get('invitation_id')

        if not invitation_id:
            return Response({"error": "Invitation ID is required"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            invitation = GroupInvitation.objects.get(
                pk=invitation_id, recipient=request.user, accepted=False)
        except GroupInvitation.DoesNotExist:
            return Response({"error": "Invitation not found or already accepted/declined"}, status=status.HTTP_404_NOT_FOUND)

        # Delete the invitation to signify that it has been declined
        invitation.delete()

        return Response({"message": "Invitation declined successfully"}, status=status.HTTP_200_OK)

# Leave group

class LeaveGroupView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        group_id = request.data.get('group_id')

        if not group_id:
            return Response({"error": "Group ID is required"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            group = Group.objects.get(pk=group_id)
            if request.user not in group.members.all():
                return Response({"error": "User is not a member of the group"}, status=status.HTTP_403_FORBIDDEN)

            # Remove the user from the group's members
            group.members.remove(request.user)

            # If the group becomes empty after a member leave, it deletes the group
            if not group.members.exists():
                group.delete()

        except Group.DoesNotExist:
            return Response({"error": "Group not found"}, status=status.HTTP_404_NOT_FOUND)

        return Response({"message": "Sucessfully left the group"}, status=status.HTTP_200_OK)


import meraki, json, os
import pandas as pd
import matplotlib.pyplot as plt

'''
    load_settings will take the Org Name and extract this data from the JSON file './settings.json'
    @params str: "org_name"
    @returns non-mutable str: API_KEY, ORG_ID, NETWORK_ID
'''
def load_settings(org_name):
    json_file = open('./settings.json') # opens file
    json_data = json.load(json_file) # load json object into mutable dict for python
    json_file.close() # close file (no mem leaks pls)

    API_KEY = json_data['API_KEY']
    ORG_ID = json_data[org_name]
    NETWORK_IDS = json_data[ORG_ID]
    HYPERION_ID = NETWORK_IDS[0][1]

    return API_KEY, ORG_ID, HYPERION_ID # return needed data for helper functions

'''
    report_loss_latency will take in a Serial, IP address with default to twitch.tv
'''
def report_loss_latency(network_id, serial, ip_addr='151.101.130.167'):
    result = dashboard.devices.getDeviceLossAndLatencyHistory(serial, ip_addr, timespan=300, resolution=60)

    try:
        for data in result:
            del data['goodput']

        json_data_query = open('./dashboard_report.json', 'w')
        json_data_query.write(json.dumps(result, indent = 4))
        json_data_query.close()
    except KeyError:
        print("Null Data -- Check API log")

'''
    Moving Graphing data to a new file for the ability to have live data get collected from the org loss/latency
    Keeping in this file for visibility and later debugging

    def graph_data(json_data):
        data_frame = pd.read_json(json_data)
        data_frame.plot()
        plt.xlabel('Duration (minutes)')
        plt.ylabel('Latency/Percent (ms/%)')
        plt.show()
'''

def remove_api_logs(num_logs_keep):
    file_dir = os.listdir()
    api_log_counter = 0
    api_log_dict = []
    for file in file_dir:
        if str(file).__contains__("meraki_api__log"):
            api_log_counter += 1
            api_log_dict.append(str(file))

    if api_log_counter > num_logs_keep:
        remove_num = api_log_counter - num_logs_keep
        for i in range(0, remove_num):
            os.remove(api_log_dict[i])

if __name__ == "__main__":
    api_key, org_id, hyperion_id = load_settings("Cisco")
    dashboard = meraki.DashboardAPI(api_key)
    response = dashboard.networks.getNetworkDevices(hyperion_id)

    serial_of_MX = ''
    for res in response:
        try:
            if res['name'] == 'MX67 - Home':
                serial_of_MX = res['serial']
        except KeyError:
            print(f'No Name -- null value: {res}')

    print(serial_of_MX) # remove later
    report_loss_latency(hyperion_id, serial_of_MX)
    remove_api_logs(num_logs_keep=5)


args = {
    # Arguments for input data for agent, and auto-encoders
    "hyper_parameters": {
        "num_epochs": 1.5e3,
        "batch_size": 1024,
        "num_channels": 3,
        "input_size": (128, 128),
        "z_dim": 64,
        "dataset": '/home/samir/Desktop/repositories/auto-features-extraction-for-RL/src/'

    },

    # Arguments for the auto-encoders
    "aae": {
        "encoder_lr": 0.0006,
        "decoder_lr": 0.0006,
        "discriminator_lr": 0.0008,
    },
    "beta_vae": {
        "C_max": 100,
        "C_stop_iter": 1e4,
        "Gamma": 1,
    },

    "wasserstein_ae": {
        "reg_weight": 100,
    },

    "vanilla_vae": {
        "M_N": 0.005,
    },

    "jigsaw_vae": {
        "M_N": 0.005,
    },

    # Arguments for the reinforcement learning
    "RL": {
        "gamma": 0.99,
        "lr": 2.5e-4,
    },

}


import argparse, subprocess

parser  = argparse.ArgumentParser()

parser.add_argument(
    "commands", # name on the CLI - drop the `--` for positional/required parameters
    nargs="*",  # 0 or more values expected => creates a list
    type=str
)

args = parser.parse_args()

print("strings: %r" % args.commands)
for c in args.commands:
    rc = subprocess.call(c,shell=True)
    if rc!=0:
        raise SystemExit("command '%s' returned %i" % (c,rc))


import tomopy
from tomopy import downsample
import os, h5py
import numpy as np
import time
import skimage.restoration as skr
import skimage
import scipy.ndimage.filters as snf
from scipy.ndimage import filters
import dxchange
from pathlib import Path
import gc, sys, tifffile
import imageio as io
from matplotlib import pyplot as plt
import scipy.ndimage as ndi
from joblib import Parallel, delayed

"""
A wrong center shift value create wrong alignment and can give errors like double boundaries.
Maybe we can try the tomopy' s built in approach "rot_center = tomopy.recon.rotation.find_center(tomo, theta, init=1265, tol=0.5, mask=True, ratio=1.0, sinogram_order=False)".
However I didn't had much luck with this when I used it.

We have a manual approach to estimate the center shift value, where print the center slice for various rotation center values and decide by going through those slices.
Maybe Brendan can give help with you understanding the entire process.
 Included in the attachments is a copy of center shift estimation jupyter notebook.
"""

def convert_to_8bit(img, vmin, vmax):
    result = np.clip(img.astype(float) - vmin, 0, vmax-vmin) / (vmax - vmin)
    return result * 255.0

def write_center(projections, white, dark, theta, dpath, center_shift_candidates, mask=False, algorithm='gridrec'):
    """ Do trial reconstructions to find the center shift.
    Inputs:
       Projections, theta = see tomopy documentation.
       dpath = filepath string. Where to save the results.
       center_shift_candidates = list of integers that define each candidate value. The value is "offset from the middle of the image", such that a value of "-1" is one pixel from the image center.
    """
    if not os.path.isdir(dpath):
        os.makedirs(dpath)

    for ii in range(0,np.size(center_shift_candidates)):
        rot_center = (projections.shape[-1] / 2) + center_shift_candidates[ii]
        projections_norm = tomopy.normalize(projections, white_avg, dark_avg)
        projections_norm = projections_norm - np.min(projections_norm) + 0.0000001
        projections_neglog = tomopy.prep.normalize.minus_log(projections_norm)
        recon = tomopy.recon(projections_neglog, theta, center=rot_center, algorithm=algorithm)

        if mask:  # Add a circular mask
            recon = tomopy.circ_mask(recon, 0, ratio=mask)

        recon = recon[0]
        vmin, vmax = np.percentile(recon, (0.02, 99.99))
        recon = convert_to_8bit(recon, vmin, vmax)

        try:
            io.imsave(os.path.join(dpath, '{:04.1f}.tiff'.format(rot_center)),
                      recon)
        except FileNotFoundError:
            os.makedirs(dpath)
            io.imsave(os.path.join(dpath, '{:04.1f}.tiff'.format(rot_center)),
                      recon)

if __name__=="__main__":

	# Read the radiographs, flat-field & dark-field images from the h5 file
	SRC_path = 'Scan Data'
	file = 'fly_scan_id_112515'
	Data = h5py.File(os.path.join(SRC_path, file + '.h5'), 'r')

	Slice_Range = slice(945,947)
	# Load the White Field images
	white = Data['img_bkg'][:,Slice_Range]
	white_avg = Data['img_bkg_avg'][0,Slice_Range]

	# Load the Dark Field Images
	dark = Data['img_dark'][:,Slice_Range]
	dark_avg = Data['img_dark_avg'][0,Slice_Range]

	# Load the Projections/Radiographs
	projections = Data['img_tomo'][:,Slice_Range]

	# Load the Angle Information
	theta = np.array(Data['angle']) * np.pi / 180

	dpath = './Center_Shift/'
	center_shift_candidates = np.arange(-50, 50, 0.5)
	write_center(projections, white_avg, dark_avg, theta, os.path.join(dpath, file), center_shift_candidates)


from flask import Flask, request, jsonify, render_template, redirect
import controladores.controlador_semestre as cont_sem
import controladores.controlador_facultad as cont_fac

app = Flask(__name__)

#semestre
@app.route('/')
@app.route("/semestres")
def semestres():
    variable1=5
    variable2=0
    semestres = cont_sem.obtener_semestre_index(variable1,variable2)
    cant = cont_sem.cant_semestres()
    editSemestre = None
    return render_template("/semestre/ListarSemestre.html", semestres = semestres, editSemestre = editSemestre, cant = cant)
@app.route("/semestres/b", methods=["POST"])
def semestres1():
    limit = request.form.get("limit")
    offset = request.form.get("offset")
    semestres = cont_sem.obtener_semestre_index(limit,offset)
    editSemestre = None
    return render_template("/semestre/tabla.html", semestres = semestres, editSemestre = editSemestre)
@app.route("/semestres/<int:id>")
def semestre_editar(id):
    semestres = cont_sem.obtener_semestre()
    semestre = cont_sem.buscar_semestre_id(id)
    #print(semestre)
    return render_template("/semestre/ListarSemestre.html", semestres = semestres, editSemestre = semestre)

@app.route("/semestres", methods=["POST"])
def semestres_nombre():
    nombre = request.form["nombre"]
    semestres = cont_sem.buscar_semestre(nombre)
    return render_template("/semestre/ListaSemestre.html", semestres = semestres, editSemestre = None)

@app.route("/agregar_semestre")
def agregar_semestre():
    return render_template("/semestre/agregar.html")
@app.route("/darbaja_semestre", methods=["POST"])
def darbaja_semestre():
    cont_sem.dar_baja(request.form["id"])
    return redirect("/semestres")
@app.route("/daralta_semestre", methods=["POST"])
def daralta_semestre():
    cont_sem.dar_alta(request.form["id"])
    return redirect("/semestres")
@app.route("/guardar_semestre", methods=["POST"])
def guardar_semestre():

    nombreSe = request.form["nombreSe"]
    fechaI = request.form["fechaI"]
    fechaF = request.form["fechaF"]
    estado = request.form["estado"]
    if estado == "Vigente":
        estado = True
    else:
        estado = False
    cont_sem.insertar_semestre(nombreSe, fechaI,fechaF,estado)

    return redirect("/semestres")

@app.route("/editar_semestre/")
def editar_semestre():
    id = request.form["idSemestre"]
    semestre = cont_sem.buscar_semestre_id(id)
    opt = [None, None]
    if(semestre[4] == 0):
        opt[0] = "selected"
    else:
        opt[1] = "selected"
    return render_template(semestre=semestre, opt=opt)

@app.route("/actualizar_semestre", methods=["POST"])
def actualizar_semestre():
    idSemestre = request.form["idSemestre"]
    nombreSe = request.form["nombreSe"]
    fechaI = request.form["fechaI"]
    fechaF = request.form["fechaF"]
    estado = request.form["estado"]
    if estado == "Vigente":
        estado = True
    else:
        estado = False

    cont_sem.actualizar_semestre(nombreSe, fechaI,fechaF,estado, idSemestre)

    return redirect("/semestres")

@app.route("/eliminar_semestre", methods=["POST"])
def eliminar_semestre():
    id = request.form["id"]
    print("El id del semestre que se quiere eliminar es", id)
    cont_sem.eliminar_semestre(id)
    return redirect("/semestres")

#facultad

@app.route("/facultades")
def facultades():
    facultades = cont_fac.obtener_facultad()
    return render_template("/facultad/listarFacultad.html", facultades = facultades)

@app.route("/facultades/<int:id>")
def facultad_editar(id):
    facultades = cont_fac.obtener_facultad()
    facultad = cont_fac.buscar_facultad_id(id)
    #print(facultad)
    return render_template("/facultad/listarFacultad.html", facultades = facultades, editFacultad = facultad)

@app.route("/facultades", methods=["POST"])
def facultades_nombre():
    nombre = request.form["nombre"]
    facultades = cont_fac.buscar_facultad(nombre)
    return render_template("/facultad/listarFacultad.html", facultades = facultades, editFacultad = None)

@app.route("/agregar_facultad")
def agregar_facultad():
    return render_template("/facultad/agregar.html")

@app.route("/guardar_facultad", methods=["POST"])
def guardar_facultad():

    nombreFa = request.form["nombreFa"]
    descripcion = request.form["descripcion"]
    estado = request.form["estado"]
    if estado == "Vigente":
        estado = True
    else:
        estado = False
    cont_fac.insertar_facultad(nombreFa,descripcion,estado)

    return redirect("facultades")

@app.route("/editar_facultad/")
def editar_facultad():
    id = request.form["idP"]
    facultad = cont_fac.buscar_facultad_id(id)
    opt = [None, None]
    if(facultad[3] == 0):
        opt[0] = "selected"
    else:
        opt[1] = "selected"
    return render_template(facultad=facultad, opt=opt)

@app.route("/actualizar_facultad", methods=["POST"])
def actualizar_facultad():
    idFacultad = request.form["idFacultad"]
    nombreFa = request.form["nombreFa"]
    descripcion = request.form["descripcion"]
    estado = request.form["estado"]
    if estado == "Vigente":
        estado = True
    else:
        estado = False

    cont_fac.actualizar_facultad(nombreFa, descripcion,estado, idFacultad)

    return redirect("facultades")

@app.route("/dar_baja", methods=["POST"])
def dar_baja():
    cont_fac.dar_baja(request.form["id"])
    return redirect("/facultades")

@app.route("/eliminar_facultad", methods=["POST"])
def eliminar_facultad():
    cont_fac.eliminar_facultad(request.form["id"])
    return redirect("/facultades")

# Iniciar el servidor
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000, debug=True)


import numpy as np
from keras.applications import VGG19
from keras.applications.vgg16 import preprocess_input, VGG16
from keras.layers import Flatten, Dense
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, accuracy_score
from keras.models import Model

import prologue
from tqdm import tqdm

#data_dir = r"C:\\Users\\mfajc\\Kaggle\\DogBreeds"
#grid, labels, train_idx, valid_idx, ytr, yv = prologue.init(data_dir)

INPUT_SIZE = 224
NUM_CLASSES= 120

vgg_bottleneck = VGG19(weights='imagenet', include_top=False, pooling='avg', classes=NUM_CLASSES)
# for layer in vgg_bottleneck.layers:
#     layer.trainable = False

# fc1 = Dense(4096, activation='relu', name='fc1')(vgg_bottleneck.output)
# fc2 = Dense(4096, activation='relu', name='fc2')(fc1)
# softmax = Dense(NUM_CLASSES, activation='softmax', name='predictions')(fc2)
#
# model = Model(inputs=vgg_bottleneck.input, outputs=softmax)
# model.compile(loss='categorical_crossentropy',
#               optimizer='adam',
#               metrics=['accuracy'])
#
# model.summary()

data_dir = r"/home/ifajcik/kaggle/dog_breed_classification/dogbreed_data"
labels, train_idx, valid_idx, ytr, yv = prologue.init(data_dir)

x_train = np.zeros((len(labels), INPUT_SIZE, INPUT_SIZE, 3), dtype='float32')
for i, img_id in tqdm(enumerate(labels['id'])):
    img = prologue.read_img(data_dir, img_id, 'train', (INPUT_SIZE, INPUT_SIZE))
    x_train[i] = preprocess_input(img)
print('Train Images shape: {} size: {:,}'.format(x_train.shape, x_train.size))

Xtr = x_train[train_idx]
Xv = x_train[valid_idx]
print((Xtr.shape, Xv.shape, ytr.shape, yv.shape))

train_vgg_bf = vgg_bottleneck.predict(Xtr, batch_size=32, verbose=1)
valid_vgg_bf = vgg_bottleneck.predict(Xv, batch_size=32, verbose=1)

print('VGG train bottleneck features shape: {} size: {:,}'.format(train_vgg_bf.shape, train_vgg_bf.size))
print('VGG valid bottleneck features shape: {} size: {:,}'.format(valid_vgg_bf.shape, valid_vgg_bf.size))

logreg = LogisticRegression(multi_class='multinomial', solver='lbfgs', random_state=prologue.SEED)
logreg.fit(train_vgg_bf, (ytr * range(NUM_CLASSES)).sum(axis=1))
valid_probs = logreg.predict_proba(valid_vgg_bf)
valid_preds = logreg.predict(valid_vgg_bf)

# model.fit(Xtr,ytr,batch_size=32,epochs=5, validation_data=(Xv, yv), verbose=1)

print('Validation VGG LogLoss {}'.format(log_loss(yv, valid_probs)))
print('Validation VGG Accuracy {}'.format(accuracy_score((yv * range(NUM_CLASSES)).sum(axis=1), valid_preds)))


from rest_framework import generics
from . import models
from rest_framework import status
from rest_framework.response import Response
from . import serializers

class NewsListView(generics.ListAPIView):
    permission_classes = ()
    queryset = models.News.objects.all()
    serializer_class = serializers.NewsSerializer

    def list(self, request, *args, **kwargs):
        order = request.query_params.get('order')
        limit = request.query_params.get('limit')
        offset = request.query_params.get('offset')

        queryset = self.queryset.all()
        allowed_params = [field.attname for field in models.News._meta.fields]
        allowed_params += ['-{}'.format(param) for param in allowed_params]

        if order:
            if order not in allowed_params:
                return Response(
                    {
                        'message': 'invalid_param'
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )

            queryset = queryset.order_by(order)

        if offset and limit:
            try:
                offset = int(offset)
                limit = int(limit)
                if limit < 0 or offset < 0:
                    return Response(
                        {
                            'message': 'negative_limit_or_offset_is_not_allowed'
                        },
                        status=status.HTTP_400_BAD_REQUEST
                    )
            except ValueError:
                return Response(
                    {
                        'message': 'invalid_param'
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )

            queryset = queryset[offset: offset + limit]

        elif offset:
            try:
                offset = int(offset)
                if offset < 0:
                    return Response(
                        {
                            'message': 'negative_offset_is_not_allowed'
                        },
                        status=status.HTTP_400_BAD_REQUEST
                    )
            except ValueError:
                return Response(
                    {
                        'message': 'invalid_param'
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )

            queryset = queryset[offset:offset + 5]

        elif limit:
            try:
                limit = int(limit)
                if limit < 0:
                    return Response(
                        {
                            'message': 'negative_limit_is_not_allowed'
                        },
                        status=status.HTTP_400_BAD_REQUEST
                    )
            except ValueError:
                return Response(
                    {
                        'message': 'invalid_param'
                    },
                    status=status.HTTP_400_BAD_REQUEST
                )

            queryset = queryset[:limit]
        else:
            queryset = queryset[:5]

        serializer = self.serializer_class(queryset,
                                           many=True)
        return Response(
            serializer.data,
            status=status.HTTP_200_OK,
        )


import sys
def eratosthenes():
    n,k = map(int,sys.stdin.readline().split())
    array = [0]*(n+1)
    count=0
    for i in range(2,n+1):
        array[i]=i
    for i in range(2, n+1):
        if (array[i]==0):
            continue

        for j in range(i,n+1,i):
            if array[j]==0:
                continue
            count+=1
            if count==k:
                print(array[j])
                exit()
            array[j]=0

if __name__ == "__main__":
    eratosthenes()


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

# In[4]:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, auc, confusion_matrix

get_ipython().run_line_magic('matplotlib', 'inline')

# In[5]:

full_data = pd.read_csv(r'\Users\Pedro\Documents\high_diamond_ranked_10min.csv')
# lets exclude gameId

data = full_data.drop(['gameId'],axis=1)

# In[6]:

# Win-loss count 0 means loss, 1 means win
blueWins = data['blueWins']
ax = sns.countplot(x = blueWins, data = data)

# In[10]:

X = data.drop(['blueWins'],axis=1)
Y = blueWins.values.reshape(-1,1)

# if memory doesnt fail, last time we fitted a logistic regression model to this data, the best result came from a train
# size of 0.9
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size = 0.9, random_state=69)

# In[11]:

# logistic regression
from sklearn.linear_model import LogisticRegression

# In[13]:

log_reg = LogisticRegression()
log_reg.fit(X_train, Y_train.ravel())

# In[14]:

Y_prob = log_reg.predict_proba(X_test)[:,1]
Y_pred = np.where(Y_prob > 0.5, 1, 0)

# In[15]:

log_confusion_matrix = confusion_matrix(Y_test, Y_pred)
log_confusion_matrix
# 390 + 358 correct predictions
# 122 + 119 wrong predictions

# In[38]:

false_positive_rate_log, true_positive_rate_log, thresholds_log = roc_curve(Y_test, Y_prob)
roc_auc_log = auc(false_positive_rate_log, true_positive_rate_log)
roc_auc_log

# In[19]:

# lets take a look at the graph

plt.figure(figsize=(9,9))
plt.title('ROC')
plt.plot(false_positive_rate_log, true_positive_rate_log, color='red', label = 'AUC = %2f' % roc_auc_log)
plt.legend(loc='lower right')
plt.plot([0,1], [0,1], linestyle = '--')
plt.axis('tight')
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.plot(roc_auc_log)

# In[20]:

# linear discriminant analysis
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

lda = LinearDiscriminantAnalysis()
lda.fit(X_train, Y_train.ravel())

# In[21]:

Y_prob_lda = lda.predict_proba(X_test)[:,1]
Y_pred_lda = np.where(Y_prob_lda > 0.5, 1, 0)

# In[23]:

lda_confusion_matrix = confusion_matrix(Y_test, Y_pred_lda)
lda_confusion_matrix

# In[24]:

false_positive_rate_lda, true_positive_rate_lda, thresholds_lda = roc_curve(Y_test, Y_prob_lda)
roc_auc_lda = auc(false_positive_rate_lda, true_positive_rate_lda)
roc_auc_lda

# In[25]:

# the auc for lda is slightly lower than the auc for the logistic regression
# this means logistic regression performs slightly better, but a very very close to zero
# roc_auc_log - roc_auc_lda

# In[26]:

plt.figure(figsize=(9,9))
plt.title('ROC')
plt.plot(false_positive_rate_lda, true_positive_rate_lda, color='red', label = 'AUC = %2f' % roc_auc_lda)
plt.legend(loc='lower right')
plt.plot([0,1], [0,1], linestyle = '--')
plt.axis('tight')
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.plot(roc_auc_lda)

# In[27]:

# finally lets see how quadratic discriminant analysis performs
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis

qda = QuadraticDiscriminantAnalysis()
qda.fit(X_train, Y_train.ravel())

# In[28]:

Y_prob_qda = qda.predict_proba(X_test)[:,1]
Y_pred_qda = np.where(Y_prob_qda > 0.5, 1, 0)

# In[29]:

qda_confusion_matrix = confusion_matrix(Y_test, Y_pred_qda)
qda_confusion_matrix

# In[30]:

false_positive_rate_qda, true_positive_rate_qda, thresholds_qda = roc_curve(Y_test, Y_prob_qda)
roc_auc_qda = auc(false_positive_rate_qda, true_positive_rate_qda)
roc_auc_qda

# In[31]:

plt.figure(figsize=(9,9))
plt.title('ROC')
plt.plot(false_positive_rate_qda, true_positive_rate_qda, color='red', label = 'AUC = %2f' % roc_auc_qda)
plt.legend(loc='lower right')
plt.plot([0,1], [0,1], linestyle = '--')
plt.axis('tight')
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.plot(roc_auc_qda)

# In[45]:

# Conclusions
# The best perfoming method was logistic regression, followed by lda, followed by qda
print('Logistic regression', '\t' , 'Lda', '\t', '                Qda')
print(roc_auc_log, '\t', roc_auc_lda, '\t', roc_auc_qda)

# In[ ]:


from datetime import datetime, timedelta

from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.utils import timezone
from notifications.signals import notify

from app.models import *
from app.urls import *
from cart.cart import *

from .forms import *
from .models import *

def order(request, coupon_code):
    cart = Cart(request)
    currency_symbol = cart.get_currency_symbol()
    currency_code = cart.get_currency_code()
    products = cart.get_cart_products()
    for product in products:
        product_id = product.id
        product = Product.objects.get(id=product_id)
    store = Store.objects.get(store_name=product.store)
    if not store.currency:
        error = (
            "Store does'nt have a set currency for payment, drop a review for the store"
        )
        return redirect("cart:cart_summary", store.slugified_store_name)
    else:
        if request.user.is_authenticated:
            user = request.user
        else:
            user = None
        if Coupon.objects.filter(code=coupon_code, created_by=store).exists():
            coupon = Coupon.objects.get(code=coupon_code, created_by=store)
            if request.user not in coupon.users.all():
                coupon.users.add(user)
                coupon_percentage = coupon.percentage
                amount = cart.get_grand_total(coupon_percentage)
            else:
                amount = cart.get_total_price()
        else:
            amount = cart.get_total_price()
        if Coupon.objects.filter(code=coupon_code, created_by=store).exists():
            coupon = True
        else:
            coupon = False
        billing_status = False
        quantity = cart.__len__()
        order = Order.objects.create(
            user=user,
            store=store,
            billing_status=billing_status,
            amount=amount,
            quantity=quantity,
            coupon=coupon,
            currency_symbol=currency_symbol,
            currency_code=currency_code,
        )
        for item in cart:
            OrderItem.objects.create(
                order=order,
                product=item["product"],
                quantity=item["qty"],
                price=item["price"],
            )
        if request.user.is_authenticated:
            message = "An order has been made on your store"
            staffs = store_staff.objects.filter(store=store)
            for staff in staffs:
                staff_user = User.objects.get(email=staff.email)
                notify.send(user, recipient=staff_user, verb=message, order=order.id)
            notify.send(user, recipient=store.owner, verb=message, order=order.id)
        return redirect("payment:initiate_payment", order.id)

def unpaid_order_mail_remainder(request):
    for order in Order.objects.filter(billing_status=False, mail_remainder=False):
        if order.user and order.date_created < timezone.now() - timedelta(days=20):
            store = Store.objects.get(store_name=order.store)
            path = f"payment/{order.id}"
            subject = f"You have unpaid order in {store.store_name} store on Shopit"
            message = render_to_string(
                "payment/unpaid-order-email.html",
                {
                    "store": store,
                    "order": order,
                    "domain": settings.DEFAULT_DOMAIN,
                },
            )
            from_email = settings.EMAIL_HOST_USER
            to_email = [order.user.email]
            send_mail(subject, message, from_email, to_email, html_message=message)


from django.conf.urls.defaults import patterns, include, url
from django.views.generic import TemplateView, CreateView, DeleteView, DetailView, ListView, UpdateView
from django.contrib.auth.decorators import login_required

from models import *
from views import *

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

urlpatterns = patterns('',
    url(r'^$', Index.as_view(), name='index'),
    #albums list
    url(r'^album/$', ListView.as_view(model = Album, template_name = 'photobook/album_list.html'), name='album_list_view'),
    #album view
    url(r'^album/(?P<pk>\d+)/$', AlbumDetailView.as_view(model=Album, template_name='photobook/album_detail.html'), name='album_detail_view'),
    #edit album
    url(r'^album/(?P<pk>\d+)/edit/$', AlbumDetailView.as_view(model=Album, template_name='photobook/album_edit.html'), name='edit_album_view'),
    #new album
    url(r'^album/create/$', login_required(create_album), name='create_album_view'),
	#page view
    url(r'^album/(?P<album>\d+)/(?P<page_number>\d+)/$', page_detail, name='page_detail_view'),
	#login view
	url(r'^login/$', 'django.contrib.auth.views.login', name="login"),
	#logout view
	url(r'^logout/$', logout_view, name="logout"),
	#register view
	url(r'^register/$', register, name="register"),
    #user list
    url(r'^user/$', login_required(ListView.as_view(model = User, template_name = 'photobook/user_list.html')), name='user_list_view'),
    #user detail view
    url(r'^users/(?P<user_name>\S+)/$', user_detail_view, name="user_detail_view"),
    #json get page information
    url(r'^album/(?P<album_id>\d+)/(?P<page_number>\d+)/json/$', get_or_save_page, name='get_or_save_page'),
    #delete album
    url(r'^album/(?P<album_id>\d+)/delete/$', delete_album, name="delete_album"),
    #delete page
    url(r'^album/(?P<album>\d+)/(?P<page_number>\d+)/delete/$', delete_page, name='delete_page'),
)


import queue

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

def PrintTree(root):
    if root == None:
        return
    print(root.data, end=':')

    if root.left != None:
        print('L', root.left.data, end=',')

    if root.right != None:
        print('R', root.right.data, end='')

    print()

    PrintTree(root.left)
    PrintTree(root.right)

def level():
    q = queue.Queue()
    rootData = int(input())

    if rootData == -1:
        return None
    root = Node(rootData)
    q.put(root)

    while not q.empty():
        cNode = q.get()

        print('Enter left child of', cNode.data)
        leftChildData = int(input())

        if leftChildData != -1:
            leftChild = Node(leftChildData)
            cNode.left = leftChild
            q.put(leftChild)

        print('Enter right child of', cNode.data)
        rightChildData = int(input())

        if rightChildData != -1:
            rightChild = Node(rightChildData)
            cNode.right = rightChild
            q.put(rightChild)
    return root

root = level()
PrintTree(root)


n = int(input())
plist = input().split()

friends = [0 for i in range(n)]

for index, pi in enumerate(plist):
    pi = int(pi)
    friends[pi - 1] = index + 1

print(" ".join(str(f) for f in friends))