from keras.applications.inception_resnet_v2 import InceptionResNetV2
from keras.models import Model
from keras.layers import GlobalAveragePooling2D, Dense
from keras.optimizers import Adam
from keras.callbacks import ReduceLROnPlateau
import tensorflow as tf

@tf.function
def Resnet50(train_generator, val_generator, epochs, batch_size, batch_size_val, total_train, total_val):
    model_finetuned = InceptionResNetV2(include_top = True, weights = 'imagenet', input_shape = (224,224,3))
    x = model_finetuned.output
    x = GlobalAveragePooling2D()(x)
    x = Dense(128, activation= 'relu')(x)
    x = Dense(64, activation= 'relu')(x)
    pridictions = Dense(4, activation='softmax')(x)
    model_finetuned = Model(inputs = model_finetuned.input, outputs = pridictions)
    opt = Adam(learning_rate=0.001)
    model_finetuned.compile(optimizer=opt, loss='categorical_crossentropy', metrics= ['accuracy'])
    history0 = model_finetuned.fit_generator(train_generator, steps_per_epoch=total_train//batch_size, epochs= epochs,
                                            validation_data= val_generator, validation_steps=total_val//batch_size,
                                            verbose= 1, callbacks=[ReduceLROnPlateau(monitor='val_loss', factor= 0.5,
                                            patience=5, min_lr=0.000001)], use_multiprocessing= False, shuffle=True)
    model_finetuned.save('E:/Document/Do An III/Joint Acne Image Grading and Counting via Label Districbution Learning/model/resnet50.h5')
    model_finetuned.summary()
    return history0


import time
import random

print("\nNumber Guessing\n")
time.sleep(1)

while True:
    valid = int(input("Press 1 for ready! "))
    if valid == 1:
        time.sleep(0.5)
        num = random.randrange(1, 10)
        while True:
            num_guess = int(input("Any Guess? "))
            if num_guess == num:
                time.sleep(0.75)
                print("Wow, you're so good at guessing!")
                break
            else:
                time.sleep(0.75)
                print("Try again!\n")
        break
    else:
        time.sleep(0.5)
        print("You have to be ready!\n")


import logging
from collections import OrderedDict
from typing import Optional

import grpc
from fastapi import APIRouter, Depends, HTTPException
from pydantic import ValidationError

from app.api.auth.permissions import Permissions
from tracardi.domain.entity import Entity
from tracardi.domain.pro_service_form_data import TProMicroserviceCredentials, ProService, ProMicroService
from tracardi.service.plugin.domain.register import Plugin, MicroserviceConfig
from tracardi.service.plugin.plugin_install import install_remote_plugin, install_plugin
from app.api.domain.credentials import Credentials
from tracardi.config import tracardi
from tracardi.domain.resource import Resource, ResourceRecord
from tracardi.domain.sign_up_data import SignUpData, SignUpRecord
from app.api.proto.tracard_pro_client import TracardiProClient
from tracardi.exceptions.log_handler import log_handler
from tracardi.service.storage.driver.elastic import resource as resource_db
from tracardi.service.storage.driver.elastic import pro as pro_db
from tracardi.service.storage.driver.elastic import action as action_db
from app.config import server
from tracardi.service.tracardi_http_client import HttpClient

logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
logger.setLevel(tracardi.logging_level)
logger.addHandler(log_handler)

router = APIRouter(
    dependencies=[Depends(Permissions(roles=["admin", "developer"]))]
)

tracardi_pro_client = TracardiProClient(host=tracardi.tracardi_pro_host,
                                        port=tracardi.tracardi_pro_port,
                                        secure=False)

async def _store_resource_record(data: Entity):
    return await resource_db.save(data)

@router.get("/tpro/validate", tags=["tpro"], include_in_schema=server.expose_gui_api)
async def is_token_valid():
    """
    Return None if not configured otherwise returns True if credentials are valid or False.
    """
    try:
        result = await pro_db.read_pro_service_endpoint()

    except ValidationError as e:
        logger.error(f"Validation error when reading pro service user data: {str(e)}")
        result = None
    except Exception as e:
        logger.error(f"Exception when reading pro service user data: {str(e)}")
        result = None

    if result is None:
        return None

    token = tracardi_pro_client.validate(token=result.token)

    return token is not None

@router.post("/tpro/sign_in", tags=["tpro"], include_in_schema=server.expose_gui_api)
async def tracardi_pro_sign_in(credentials: Credentials):
    """
    Handles signing in to Tracardi PRO service
    """
    try:
        token, host = tracardi_pro_client.sign_in(credentials.username, credentials.password)
        result = await pro_db.read_pro_service_endpoint()

        # Save locally if data from remote differs with local data.
        if result is None or result.token != token:
            sign_up_record = SignUpRecord(id='0', token=token)
            result = await pro_db.save_pro_service_endpoint(sign_up_record)

            if result.saved == 0:
                raise ConnectionError("Could not save Tracardi Pro data.")

        return True
    except PermissionError as e:
        msg = "Access denied due to server error:  {}".format(str(e))
        logger.warning(msg, exc_info=True)
        raise HTTPException(detail=msg,
                            status_code=403)  # Must be 403 because 401 logs out gui
    except Exception as e:
        logger.error(str(e), exc_info=True)
        raise HTTPException(detail=str(e), status_code=403)  # Must be 403 because 401 logs out gui

@router.post("/tpro/sign_up", tags=["tpro"], include_in_schema=server.expose_gui_api, response_model=bool)
async def tracardi_pro_sign_up(sign_up_data: SignUpData):
    """
    Handles signing up to Tracardi PRO service
    """
    try:
        # todo save more contact data on Pro server
        token = tracardi_pro_client.sign_up(sign_up_data.username, sign_up_data.password)
        sign_up_record = SignUpRecord(id='0', token=token)
        result = await pro_db.save_pro_service_endpoint(sign_up_record)

        if result.saved == 0:
            raise ConnectionError("Could not save Tracardi Pro endpoint.")

        return True

    except grpc.RpcError as e:
        raise HTTPException(
            detail="Access denied due to RPC error \"{}\". Error status: {}".format(e.details(), e.code().name),
            status_code=403)  # Must be 403 because 401 logs out gui

@router.get("/tpro/available_services", tags=["tpro"], include_in_schema=server.expose_gui_api)
async def get_available_services(query: Optional[str] = "", category: Optional[str] = ""):
    """
    Returns available Tracardi PRO services
    """
    try:
        services = await tracardi_pro_client.get_available_services(query, category)
        if 'services' in services:
            services['services'] = OrderedDict(sorted(services['services'].items()))
            return services

        return {
            "services": {}
        }
    except grpc.RpcError as e:
        # Must be 403 because 401 logs out gui
        raise HTTPException(detail=e.details(), status_code=403 if e.code().name == 'UNAUTHENTICATED' else 500)

@router.get("/tpro/plugin/{module}", tags=["tpro"], include_in_schema=server.expose_gui_api)
async def get_available_services(module: str):
    """
    Returns available Tracardi PRO services
    """
    try:
        return await tracardi_pro_client.get_plugin(module)

    except grpc.RpcError as e:
        # Must be 403 because 401 logs out gui
        raise HTTPException(detail=e.details(), status_code=403 if e.code().name == 'UNAUTHENTICATED' else 500)

@router.post("/tpro/install", tags=["tpro"], include_in_schema=server.expose_gui_api)
async def save_tracardi_pro_resource(pro: ProService):
    """
    Adds new Tracardi PRO resource
    """
    result = {}

    # Add resource

    if 'resource' in pro.service.metadata.submit:
        resource = Resource.from_pro_service(pro)

        def _remove_redundant_data(credentials):
            credentials.pop('name', None)
            credentials.pop('description', None)
            return credentials

        resource.credentials.production = _remove_redundant_data(resource.credentials.production)
        resource.credentials.test = _remove_redundant_data(resource.credentials.test)

        record = ResourceRecord.encode(resource)
        result['resource'] = await _store_resource_record(record)
        await resource_db.refresh()

    # Add plugins

    if isinstance(pro.plugins, list):
        result['plugin'] = []
        for plugin in pro.plugins:
            plugin = Plugin(**plugin)
            response = await install_plugin(plugin.spec.module)
            result['plugin'].append(response)
        await action_db.refresh()

    return result

@router.post("/tpro/install/microservice", tags=["tpro"], include_in_schema=server.expose_gui_api)
async def save_tracardi_pro_microservice(pro: ProMicroService):
    """
    Adds new Tracardi PRO resource
    """

    resource = Resource.from_pro_service(pro)

    def _remove_redundant_data(credentials):
        credentials.pop('name', None)
        credentials.pop('description', None)
        return credentials

    resource.credentials.production = _remove_redundant_data(resource.credentials.production)
    resource.credentials.test = _remove_redundant_data(resource.credentials.test)

    production_credentials = TProMicroserviceCredentials(**resource.credentials.production)

    record = ResourceRecord.encode(resource)
    result = await _store_resource_record(record)
    await resource_db.refresh()

    # Create plugin

    if not pro.microservice.service.id or not production_credentials.is_configured():
        raise AssertionError("Microservice Host, Token or Service not configured")

    microservice_plugin_url = f"{production_credentials.url}/plugin/registry?service_id={pro.microservice.service.id}"

    async with HttpClient(3, 200, headers={
        'Authorization': f"Bearer {production_credentials.token}"
    }) as client:
        async with client.get(url=microservice_plugin_url) as response:
            data = await response.json()

            if response.status != 200:
                raise HTTPException(status_code=response.status, detail=data)

            plugin = Plugin(**data)

            plugin.metadata.name = resource.name

            if plugin.spec.microservice is None:
                plugin.spec.microservice = MicroserviceConfig.create()

            plugin.spec.microservice.service.id = pro.microservice.service.id
            plugin.spec.microservice.service.name = pro.microservice.service.name
            # Set credentials, exclude service data
            plugin.spec.microservice.server.credentials = resource.credentials
            # Configure microservice to be connected with created resource
            plugin.spec.microservice.server.resource.name = resource.name
            plugin.spec.microservice.server.resource.id = resource.id
            # Plugin resources
            plugin.spec.microservice.plugin.resource = pro.microservice.credentials

            await install_remote_plugin(plugin)

    return result


import json

def getSentences(filename):
    sentences = []
    with open(filename, "r", encoding="utf-8") as f:
        for line in f:
            temp = []
            documents = json.loads(line)
            for content in documents:
                sentence = content["sentence"]
                temp.append(sentence)
            sentences.append(temp)
    return sentences

def work(task):
    small = "data/" + task + "/data_small_selected.json"
    large = "data/" + task + "/train_selected.json"
    oufname = "data/" + task + "/pretrain.txt"
    all_sentences = []
    small_sentences = getSentences(small)
    large_sentences = getSentences(large)
    all_sentences.extend(small_sentences)
    all_sentences.extend(large_sentences)
    ouf = open(oufname, "w", encoding="utf-8")
    for document in all_sentences:
        for sentence in document:
            ouf.write(str(sentence) + "\n")
        ouf.write("\n")
    ouf.close()

if __name__ == '__main__':
    tasks = ["divorce", "labor", "loan"]
    for task in tasks:
        work(task)


import sys
import unittest
from ddt import ddt, data, unpack
import src.dqn.dqn as target

# The code below unittest learnbackprop (a little bit complicated)

class Build_Test_Model(target.nn.Module):

    # This fake model only has one weight. It has the following formula:
    #    output = input * weight(initialized to be 2)
    #    loss = (target-output)^2 = output^2 -2*output*target + target*2
    #    Gradient = dloss/dw = dloss/doutput * doutput/dw = (2 * output-2*target) * input = 2*(output-target)*input
    #    weight = weight - gradient*lr

    def __init__(self):
        super(Build_Test_Model, self).__init__()
        self.nn_layers = target.nn.ModuleList([target.nn.Linear(1, 1, bias=False)])
        # learning rate is fixed as 0.1
        # Use SGD instead of Adam because it is easier to calculate gradient update
        self.optimizer = target.optim.SGD(self.parameters(), lr= 0.1)
        self.loss = target.nn.MSELoss()
        target.torch.nn.init.constant_(self.nn_layers[0].weight, 2)
        self.device = target.torch.device('cuda:0' if target.torch.cuda.is_available() else 'cpu')
        self.to(self.device)

    def forward(self, state):
        state = target.torch.tensor(state, dtype=target.torch.float32).to(self.device)
        state = self.nn_layers[0](state)
        return state

class Fake_LearnFromOneSample(object):
    # This fake function always return prediction = 4, target = 7 if the above fake model is passed in
    def __call__(self, model, target_model, episode):
        state = target.torch.tensor([2], dtype=target.torch.float32)
        pred = model(state)
        result_target = target.torch.tensor([7], dtype=target.torch.float32)
        return pred, result_target

test_model = Build_Test_Model()
test_target_model = test_model
test_learn = Fake_LearnFromOneSample()
# The minibatch is not important as the model always return prediction =4, target = 7
test_minibatch = [5]

# begin to unittest if the back propogration is correctly calculated
@ddt
class testlearnbackprop(unittest.TestCase):
    # The new weight should be 3.2 after one iteration of training: 2-2*(4-7)*2*lr = 2-(-1.2) = 3.2. Formula for the update is shown above
    @data((test_model,test_target_model,test_learn,test_minibatch,3.2))
    @unpack
    def test(self, test_model,test_target_model,test_learn,test_minibatch,expected_weight):
        test_model = target.learnbackprop(test_model,test_target_model,test_minibatch,test_learn)
        calculated_weight = [param for param in test_model.parameters()][0]
        self.assertAlmostEqual(calculated_weight, expected_weight, places = 3)

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)


#!/usr/bin/env python -u
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# police-mvd.py
# Author: Maxim Dubinin (sim@gis-lab.info)
# About: Grab 112.ru data on ó÷àñòêîâûå, creates two tables linked with unique id, policemen and locations they are responsible for.
# Created: 13:26 07.05.2013
# Usage example: python police-mvd.py 45000000000
# ---------------------------------------------------------------------------

from bs4 import BeautifulSoup
import urllib2
import csv
import requests

def get_subj_list(link):
    u = urllib2.urlopen(link)
    r = u.read()
    f = open("codes/subjects.html","wb")
    f.write(r)
    f.close()

def proc_subj_list():
    f = open("codes/subjects.html")
    soup = BeautifulSoup(''.join(f.read()),"lxml")
    subj_select = soup.find("select", { "class" : "subject select" })
    subjs = subj_select.findAll("option", { "class" : "data" })
    for subj in subjs:
        name = subj.text.encode("utf-8")
        code = subj['value']
        csvwriter.writerow(dict(NAME1=name,
                            CODE1=code))

def get_mun_list(code1):
    link = "http://mvd.ru/kladr/subzone_option/" + code1
    r = requests.get(link)

    f_subj_subzone = open("codes/subj_subzone_" + code1 + ".txt","wb")
    f_subj_subzone.write(r.text)
    f_subj_subzone.close()

def proc_mun_list(code1,name1):
    f_subj_subzone = open("codes/subj_subzone_" + code1 + ".txt")
    soup = BeautifulSoup(''.join(f_subj_subzone.read()),"lxml")
    options = soup.findAll("option")

    #empty line for cases when next level is empty (Москва (г))
    csvwriter_subzone.writerow(dict(NAME1=name1,
                            CODE1=code1,
                            NAME2="",
                            CODE2=""))

    for option in options:
        name2 = option.text
        code2 = option['value'].replace('\\"','')
        csvwriter_subzone.writerow(dict(NAME1=name1,
                            CODE1=code1,
                            NAME2=name2.decode('unicode_escape').encode("utf-8"),
                            CODE2=code2))

def get_city_list(code2):
    link = "http://mvd.ru/kladr/city_zone_option/" + code2
    r = requests.get(link)

    f_subj_subzone = open("codes/subj_cityzone_" + code2 + ".txt","wb")
    f_subj_subzone.write(r.text)
    f_subj_subzone.close()

def proc_city_list(code1,name1,code2,name2):
    f_cityzone = open("codes/subj_cityzone_" + code2 + ".txt")
    soup = BeautifulSoup(''.join(f_cityzone.read()),"lxml")
    options = soup.findAll("option")

    #empty line for cases when next level is empty
    csvwriter_cityzone.writerow(dict(NAME1=name1,
                            CODE1=code1,
                            NAME2=name2,
                            CODE2=code2,
                            NAME3="",
                            CODE3=""))

    for option in options:
        name3 = option.text
        code3 = option['value'].replace('\\"','')
        csvwriter_cityzone.writerow(dict(NAME1=name1,
                            CODE1=code1,
                            NAME2=name2,
                            CODE2=code2,
                            NAME3=name3.decode('unicode_escape').encode("utf-8"),
                            CODE3=code3))

if __name__ == '__main__':
    subj_page_link = "http://mvd.ru/help/district"

    #subject level
    fieldnames_data = ("NAME1","CODE1")
    f_subj = open("codes/codes_subj.csv","wb")
    csvwriter = csv.DictWriter(f_subj, fieldnames=fieldnames_data)
    get_subj_list(subj_page_link)
    proc_subj_list()
    f_subj.close()

    #rayon+city district level
    f_subj = open("codes/codes_subj.csv")
    csvreader = csv.DictReader(f_subj, fieldnames=fieldnames_data)
    f_subzone = open("codes/codes_subzone.csv","wb")
    fieldnames_data = ("NAME1","CODE1","NAME2","CODE2")
    csvwriter_subzone = csv.DictWriter(f_subzone, fieldnames=fieldnames_data)
    for row in csvreader:
        print(row['NAME1'])
        get_mun_list(row['CODE1'])
        proc_mun_list(row['CODE1'],row['NAME1'])
    f_subj.close()
    f_subzone.close()

    #settlement level
    f_subzone = open("codes/codes_subzone.csv")
    csvreader = csv.DictReader(f_subzone, fieldnames=fieldnames_data)
    f_cityzone = open("codes/codes_cityzone.csv","wb")
    fieldnames_data = ("NAME1","CODE1","NAME2","CODE2","NAME3","CODE3")
    csvwriter_cityzone = csv.DictWriter(f_cityzone, fieldnames=fieldnames_data)
    for row in csvreader:
        print(row['NAME2'])
        get_city_list(row['CODE2'])
        proc_city_list(row['CODE1'],row['NAME1'],row['CODE2'],row['NAME2'])
    f_subzone.close()
    f_cityzone.close()


import functools
import os
import requests

from qobuz import config
from qobuz.debug import getLogger
from qobuz.util.common import get_default_image_size
from qobuz.util.file import unlink
from qobuz.util.hash import hashit
from qobuz.util.random import randrange

COMBINED_COVER_FMT = 'cover-{nid}-{size_w}-{size_h}-{count}-combine.jpg'
TMPIMG_FMT = 'tmp-img.jpg'
HASHED_ALBUM_COVER_FMT = 'cache-album-cover-{}.jpg'

logger = getLogger(__name__)
PIL_AVAILABLE = False

try:
    from PIL import Image
    PIL_AVAILABLE = True
except ImportError as e:
    logger.error('Cannot import PIL library')

def _mywalk(path):
    for dirpath, _dirnames, filenames in os.walk(path):
        for name in filenames:
            yield name, os.path.join(dirpath, name)

def _find_all_combined_images(covers_path):
    for name, full_path in _mywalk(covers_path):
        if not name.endswith('.jpg'):
            continue
        yield full_path

def cleanfs_combined_covers():
    ''' Clean all images under __covers_path__
    '''
    covers_path = config.path.combined_covers
    for filename in _find_all_combined_images(covers_path):
        unlink(filename)

def next_image_generator_factory(images):
    ''' Yield image path from images array indefinitly (reset to 0)
    '''
    index = 0
    size = len(images)
    while True:
        if index >= size:
            index = 0
        ret = images[index]
        yield ret
        index += 1

def get_remote_image(url):
    ''' get image from url and return path from local file'''
    covers_path = config.path.combined_covers
    hashed_filename = HASHED_ALBUM_COVER_FMT.format(
        hashit(url))
    new_path = os.path.join(covers_path, hashed_filename)

    if not os.path.exists(new_path):
        img_request = requests.get(url, stream=True)
        if img_request.status_code != 200:
            logger.warn('GetRemoteImageError %s', img_request.status_code)
            return None
        with open(new_path, 'wb') as write_handle:
            write_handle.writelines(img_request.iter_content(1024))
            write_handle.flush()
    return new_path

def _resize_image(img_path, thumb_size_w):
    try:
        part = Image.open(img_path)
        new_height = thumb_size_w * part.height / part.width
        return part.resize((thumb_size_w, new_height), Image.ANTIALIAS)
    except Exception as e:
        logger.error('ResizeImageError %s', e)
    return None

def _combine_factory_final_path(count, nid, img_size):
    size_w, size_h = img_size
    covers_path = config.path.combined_covers
    filename = COMBINED_COVER_FMT.format(
        count=count,
        nid=nid,
        size_h=size_h,
        size_w=size_w
    )
    return os.path.join(covers_path, filename)

def _combine_factory_build_one(thumb_size,
                               image_path_generator,
                               new_image,
                               rowcol):
    img_path = next(image_path_generator)
    if img_path.startswith('http'):
        img_path = get_remote_image(img_path)
    image = _resize_image(img_path, thumb_size[0])
    try:
        new_image.paste(image, (rowcol[0] * thumb_size[0],
                            rowcol[1] * thumb_size[1]))
    except:
        logger.warn("new_image paste failed")

def _combine_factory_build(final_path, img_size, count, image_path_generator):
    new_image = Image.new('RGB', img_size)
    demi_count = count / 2
    thumb_size = (
        int(img_size[0] / demi_count),
        int(img_size[1] / demi_count)
    )

    for i in range(0, demi_count):
        for j in range(0, demi_count):
            _combine_factory_build_one(thumb_size,
                                       image_path_generator,
                                       new_image,
                                       (i, j))

    new_image.save(final_path)
    return final_path

def _combine_nopil(_nid, images=None):
    if not images:
        return None
    return images[randrange(0, len(images) - 1)]

def _combine_pil(nid, images=None):
    ''' Combine the first 4 images of images array into single image '''
    count = 4
    img_size = get_default_image_size()
    image_path_generator = next_image_generator_factory(images)
    final_path = _combine_factory_final_path(count, nid, img_size)
    if os.path.exists(final_path):
        return final_path
    return _combine_factory_build(final_path,
                                  img_size,
                                  count,
                                  image_path_generator)

def combine_factory(pil_available, nid, images=None):
    if not config.app.registry.get('image_create_mosaic', to='bool'):
        pil_available = False
    if pil_available is True and len(images) > 1:
        return _combine_pil(nid, images=images)
    return _combine_nopil(nid, images=images)

combine = functools.partial(combine_factory, PIL_AVAILABLE)


import decimal

from rest_framework import serializers

from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone

from .models import AccountBalance, Transfer

class BalanceSerializer(serializers.ModelSerializer):
    user = serializers.CharField(source="account")

    class Meta:
        model = AccountBalance
        exclude = ["account"]
        extra_kwargs = {"currency": {"read_only": True}}

class TransferCreateSerializer(serializers.Serializer):
    from_account = serializers.CharField()
    to_account = serializers.CharField()
    amount = serializers.DecimalField(max_digits=20, decimal_places=2)

    class Meta:
        fields = ("from_account", "amount", "to_account")

    def create(self, validated_data):
        """Lock related accounts, add transfers, and update accounts' balances

        Raises:
            ValidationError: when amount is invalid
        """
        prim_account = validated_data.pop("from_account")
        sec_account = validated_data.pop("to_account")
        amount = validated_data.pop("amount")

        if decimal.Decimal(amount) < decimal.Decimal("0.0"):
            raise ValidationError("amount can't be negative")

        with transaction.atomic():
            # Lock accounts' balance row, preventing anyone else from changing the balance
            prim_acc_ins = AccountBalance.objects.select_for_update().filter(
                account=prim_account
            )
            AccountBalance.objects.select_for_update().filter(account=sec_account)

            # Update the primary account's balance and add a Transfer row atomically
            prim_acc_ins = AccountBalance.objects.get(account=prim_account)
            prim_acc_ins.balance = prim_acc_ins.balance - decimal.Decimal(amount)
            prim_acc_ins.full_clean()
            prim_acc_ins.save()

            # Update the secondary account's balance and add a Transfer row atomically
            sec_acc_ins = AccountBalance.objects.get(account=sec_account)
            sec_acc_ins.balance = sec_acc_ins.balance + decimal.Decimal(amount)
            sec_acc_ins.save()

            timestamp = timezone.now()
            t1 = Transfer.objects.create(
                primary_account=prim_acc_ins,
                secondary_account=sec_acc_ins,
                amount=amount,
                direction="outgoing",
                timestamp=timestamp,
            )

            Transfer.objects.create(
                primary_account=sec_acc_ins,
                secondary_account=prim_acc_ins,
                amount=amount,
                direction="incoming",
                timestamp=timestamp,
            )
            return t1

class TransferListSerializer(serializers.ModelSerializer):
    account = serializers.CharField(source="primary_account.account")

    class Meta:
        model = Transfer
        exclude = ["primary_account", "id", "secondary_account"]
        read_only_fields = ["timestamp", "direction"]

    def to_representation(self, obj):
        seco_account_type = serializers.CharField(source="secondary_account.account")
        if obj.direction == "outgoing":
            self.fields["to_account"] = seco_account_type
            self.fields.pop("from_account", None)
        else:
            self.fields["from_account"] = seco_account_type
            self.fields.pop("to_account", None)

        try:
            del self._readable_fields  # Clear the cache
        except AttributeError:
            pass
        return super().to_representation(obj)


from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from msrest.authentication import CognitiveServicesCredentials
import os

class _CvClient:
    def __init__(self):
        subscription_key = os.environ.get('SUBSCRIPTION_KEY')
        endpoint = os.environ.get('IMAGE_SIMILARITY_ENDPOINT')
        self.client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

    def get_top_tags_from_url(self, img_url: str, top_n: int):
        """
        Return topN tags for the imageURL as a List
        """
        tag_results = self.client.tag_image(img_url).tags
        tag_names = [x.name for x in tag_results]
        return tag_names[:top_n]

    def get_top_tags_from_stream(self, img_path: str, top_n: int):
        """
        Return topN tags for the imageStream as a List
        """
        img = open(img_path, 'r+b')
        tag_results = self.client.tag_image_in_stream(img).tags
        tag_names = [x.name for x in tag_results]
        return tag_names[:top_n]

    def check_similar(self, img1_url: str, img2_path: str):
        tag_names1 = self.get_top_tags_from_url(img1_url, 5)
        tag_names2 = self.get_top_tags_from_stream(img2_path, 5)
        print(tag_names1, tag_names2)
        if(
                len(set(tag_names1).intersection(set(tag_names2))) >= min(max(len(tag_names1), len(tag_names2)), 4)
        ):
            return True
        else:
            return False

cv_client = _CvClient()


class UserCompliance:

    @staticmethod
    def subject_is_adult(user, country_code):
        """
        Check if the user is of legal adult age in their country.

        Args:
        - user: The user for whom you want to check compliance.
        - country_code: The user's country code (e.g., 'FR' for France).

        Returns:
        - True if the user is an adult, False otherwise.
        """
        # Implement age-based compliance checks specific to the user's country
        # Example: Check the legal age for adulthood in the user's country
        legal_adult_age = UserCompliance.get_legal_adult_age(country_code)
        user_age = user.get_age()  # Replace with your actual logic to get the user's age
        return user_age >= legal_adult_age

    @staticmethod
    def subject_is_not_adult(user, country_code):
        """
        Check if the user is not of legal adult age in their country.

        Args:
        - user: The user for whom you want to check compliance.
        - country_code: The user's country code (e.g., 'FR' for France).

        Returns:
        - True if the user is not an adult, False otherwise.
        """
        return not UserCompliance.subject_is_adult(user, country_code)

    @staticmethod
    def get_legal_adult_age(country_code):
        """
        Get the legal age for adulthood in a specific country.

        Args:
        - country_code: The country code for which you want to retrieve the legal adult age.

        Returns:
        - The legal age for adulthood in the specified country.
        """
        # Implement logic to fetch the legal adult age for the specified country
        # Example: Use a dictionary of legal adult ages by country code
        legal_adult_age_by_country = {
            'FR': 18,  # Legal adult age in France
            # Add more countries and legal adult ages as needed
        }
        # Default to 18 if not found
        return legal_adult_age_by_country.get(country_code, 18)

    # Additional compliance checks and methods specific to EU regulations


# Capocollo Recipe
#
# C 2021 Stoyanov
#
# 1000 g Pork neck
# 15 g Sea salt
# 10 g Nitrite salt
# 5 g Sugar
# 2 days per 500 g

def nitro_salt(m):
    # 1000/10 = m/x
    try:
        m = int(m)
    except:
        m = 0
    return int(10 * m / 1000)


# function to calculate grade based on deviation from class average
def calculateGrade(mark, class_avg):
    deviation = mark - class_avg
    if deviation >= 20:
        return 'S'
    elif deviation >= 10:
        return 'A'
    elif deviation >= -5 and deviation <= 5:
        return 'B'
    elif deviation <= 10:
        return 'C'
    elif deviation <= 15:
        return 'D'
    else:
        return 'F'

# main program
mark = int(input("Enter the marks secured by the student: "))
class_avg = int(input("Enter the average marks of the class: "))
grade = calculateGrade(mark, class_avg)
print("The grade secured by the student is:", grade)


from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

import time

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __str__(self):
        n = 'null' if not self.next else self.next.val
        return ' [val=%s, next=%s] ' % (self.val, n)

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 and not l2:
            return None
        h1 = l1
        h2 = l2
        l3 = ListNode(0)
        h3 = l3

        while h1 or h2 or h3:
            # print('start ---> ', h1, h2, h3)
            v = 0
            if h1:
                v += h1.val
                h1 = h1.next
            if h2:
                v += h2.val
                h2 = h2.next
            if h3:
                v += h3.val

            if v >= 10:
                h3.val = v % 10
                if h3.next:
                    print('h3 yes next ...')
                    h3.next.val += 1
                else:
                    print('h3 no next ...')
                    h3.next = ListNode(0)
                    h3.next.val += 1
                h3 = h3.next
            else:
                h3.val = v
                if h1 or h2:
                    if not h3.next:
                        h3.next = ListNode(0)
                h3 = h3.next
            # print('end ---< ', h1, h2, h3)
            # time.sleep(1)

        return l3

n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)

nl1 = n1
n1.next = n2
n2.next = n3

n11 = ListNode(4)
n21 = ListNode(9)
n31 = ListNode(9)

nl2 = n11
n11.next = n21
n21.next = n31

print(nl1.val, nl1.next.val, nl1.next.next.val)
print(nl2.val, nl2.next.val, nl2.next.next.val)
nl = Solution().addTwoNumbers(nl1, nl2)
while nl:
    print(nl.val)
    nl = nl.next


# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

from __future__ import print_function
import tensorflow as tf
import numpy as np

import TensorflowUtils as utils
import read_MITSceneParsingData as scene_parsing
import datetime
import BatchDatasetReader as dataset
import cv2
import os
from six.moves import xrange

FLAGS = tf.flags.FLAGS

tf.flags.DEFINE_integer('batch_size', '2', 'batch size for training/testing')
tf.flags.DEFINE_string('logs_dir', 'logs/', 'path to logs directory')
tf.flags.DEFINE_string('data_dir', 'Data_zoo/MIT_SceneParsing/', 'path to dataset')
tf.flags.DEFINE_string('data_name', 'ADEChallengeData2016', 'data name')
tf.flags.DEFINE_float('learning_rate', '1e-5', 'initial learning rate for Adam Optimizer')
tf.flags.DEFINE_string('model_path', 'Model_zoo/imagenet-vgg-verydeep-19.mat', 'path to vgg FLAGS.model mat')
tf.flags.DEFINE_bool('debug', 'False', 'debug mode: True/False')
tf.flags.DEFINE_string('mode', 'train', 'mode train/visualize')
tf.flags.DEFINE_float('weight_decay', '1e-3', 'L2 regularization, decay=0.0 means no L2')

tf.flags.DEFINE_integer('MAX_ITERATION', '100001', 'upper limit of iterations')
tf.flags.DEFINE_integer('NUM_OF_CLASSES', '3', 'number of classes detected including background = # of real class + 1')
tf.flags.DEFINE_integer('IMAGE_SIZE', '224',
                        'image size for height and weight at the same time. Suggested size is 32 times, 224/32 = 7')

# batch_size = 1  # batch 大小
# logs_dir = "logs/"
# data_dir = "Data_zoo/MIT_SceneParsing/"  # 存放数据集的路径，需要提前下载
# data_name = "ADEChallengeData2016"
# learning_rate = 1e-5  # 学习率
# model_path = "Model_zoo/imagenet-vgg-verydeep-19.mat"  # VGG网络参数文件，需要提前下载
# debug = False
# mode = 'visualize'  # 训练模式train | visualize
#
# modeL_URL = 'http://www.vlfeat.org/matconvnet/FLAGS.models/beta16/imagenet-vgg-verydeep-19.mat'  # 训练好的VGGNet参数
#
# MAX_ITERATION = int(1e5 + 1)  # 最大迭代次数
# NUM_OF_CLASSES = 3  # 类的个数
# IMAGE_SIZE = 224  # 图像尺寸

# 根据载入的权重建立原始的 VGGNet 的网络
def vgg_net(weights, image):
    """
        weights ????
        image ????
    """

    # 2+2+4+4+4 = 16 : VGG-19:16 conv + 3 fully connected layer
    layers = (
        'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
        'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
        'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
        'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',
        'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4'
    )

    net = {}
    current = image

    for i, name in enumerate(layers):
        kind = name[:4]  # conv,relu,pool

        if kind == 'conv':
            kernels, bias = weights[i][0][0][0][0]
            # matconvnet: weights are [width, height, in_channels, out_channels]
            # tensorflow: weights are [height, width, in_channels, out_channels]

            kernels = utils.get_variable(np.transpose(kernels, [1, 0, 2, 3]), name=name + '_w')
            bias = utils.get_variable(bias.reshape(-1), name=name + '_b')
            current = utils.conv2d_basic(current, kernels, bias, FLAGS.weight_decay)

            print('current shape: ', np.shape(current))
        elif kind == 'relu':
            current = tf.nn.relu(current, name=name)
            if FLAGS.debug:
                utils.add_activation_summary(current)
        elif kind == 'pool':
            current = utils.avg_pool_2x2(current)
            print('current shape: ', np.shape(current))
        net[name] = current

    return net

# FCN的网络结构定义，网络中用到的参数是迁移VGG训练好的参数
def inference(image, keep_prob):
    """
    Semantic segmentation network definition
    : param image: input image, should have values in range 0-255
    : param keep_prob
    : return:
    """

    # loading FLAGS.model
    print('original image', np.shape(image))

    model_data = utils.get_model_data(FLAGS.model_path)

    # mean = model_data['normalization'][0][0][0]
    # mean_pixel = np.mean(mean, axis=(0, 1))  # array([123.68 , 116.779, 103.939])

    mean_pixel = np.array([134.69] * 3)

    weights = np.squeeze(model_data['layers'])

    # image preprocessing
    processed_image = utils.process_image(image, mean_pixel)
    print('preprocessed image: ', np.shape(processed_image))

    with tf.variable_scope('inference'):
        # build original VGGNET-19
        print('start building VGG')
        image_net = vgg_net(weights, processed_image)

        # 在VGGNet-19之后添加 一个池化层和三个卷积层
        conv_final_layer = image_net['conv5_3']
        print("VGG处理后的图像：", np.shape(conv_final_layer))

        pool5 = utils.max_pool_2x2(conv_final_layer)  # batch x 7 x7 x 512

        print('pool5', np.shape(pool5))

        W6 = utils.weight_variable([7, 7, 512, 4096], name="W6")
        b6 = utils.bias_variable([4096], name='b6')
        conv6 = utils.conv2d_basic(pool5, W6, b6, FLAGS.weight_decay)
        relu6 = tf.nn.relu(conv6, name='relu6')

        if FLAGS.debug:
            utils.add_activation_summary(relu6)

        relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob)

        print('conv6:', np.shape(relu_dropout6))

        W7 = utils.weight_variable([1, 1, 4096, 4096], name="W7")
        b7 = utils.bias_variable([4096], name="b7")
        conv7 = utils.conv2d_basic(relu_dropout6, W7, b7, FLAGS.weight_decay)
        relu7 = tf.nn.relu(conv7, name="relu7")
        if FLAGS.debug:
            utils.add_activation_summary(relu7)
        relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)

        print("conv7:", np.shape(relu_dropout7))

        W8 = utils.weight_variable([1, 1, 4096, FLAGS.NUM_OF_CLASSES], name="W8")
        b8 = utils.bias_variable([FLAGS.NUM_OF_CLASSES], name="b8")
        conv8 = utils.conv2d_basic(relu_dropout7, W8, b8, FLAGS.weight_decay)

        print("conv8:", np.shape(conv8))  # batch x 7 x 7 x 151
        # annotation_pred1 = tf.argmax(conv8, dimension=3, name="prediction1")

        # 对卷积后的结果进行反卷积操作

        deconv_shape1 = image_net["pool4"].get_shape()  # 14x14x512
        W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, FLAGS.NUM_OF_CLASSES], name="W_t1")
        b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1")
        conv_t1 = utils.conv2d_transpose_strided(conv8, W_t1, b_t1,
                                                 output_shape=tf.shape(image_net["pool4"]))  # 14x14x512
        fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1")

        print("pool4 and de_conv8 ==> fuse1:", np.shape(fuse_1))  # (14, 14, 512)

        deconv_shape2 = image_net["pool3"].get_shape()  # 28x28x256
        W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value],
                                     name="W_t2")  # [4,4,256,512].
        b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2")  # 256
        conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2,
                                                 output_shape=tf.shape(image_net["pool3"]))  # 28x28x256
        fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2")

        print("pool3 and deconv_fuse1 ==> fuse2:", np.shape(fuse_2))  # (28, 28, 256)

        shape = tf.shape(image)  # 1x224x224x3
        deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], FLAGS.NUM_OF_CLASSES])  # 224x224X3X151
        W_t3 = utils.weight_variable([16, 16, FLAGS.NUM_OF_CLASSES, deconv_shape2[3].value],
                                     name="W_t3")  # [16,16,151,256]
        b_t3 = utils.bias_variable([FLAGS.NUM_OF_CLASSES], name="b_t3")
        conv_t3 = utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)

        print("conv_t3:", [np.shape(image)[1], np.shape(image)[2], FLAGS.NUM_OF_CLASSES])  # (224,224,151)

        annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction")  # (224,224,1)

    return tf.expand_dims(annotation_pred, dim=3), conv_t3

# 返回优化器
def train(loss_val, var_list):
    optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)
    grads = optimizer.compute_gradients(loss_val, var_list=var_list)
    if FLAGS.debug:
        # print(len(var_list))
        for grad, var in grads:
            utils.add_gradient_summary(grad, var)
    return optimizer.apply_gradients(grads)

# 主函数,返回优化器的操作步骤http://www.vlfeat.org/matconvnet/FLAGS.models/beta16/imagenet-vgg-verydeep-19.mat
def main(argv=None):
    keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
    image = tf.placeholder(tf.float32, shape=[None, FLAGS.IMAGE_SIZE, FLAGS.IMAGE_SIZE, 3], name="input_image")
    annotation = tf.placeholder(tf.int32, shape=[None, FLAGS.IMAGE_SIZE, FLAGS.IMAGE_SIZE, 1], name="annotation")

    print("setting up vgg initialized conv layers ...")

    # 定义好FCN的网络模型
    pred_annotation, logits = inference(image, keep_probability)

    labels = tf.squeeze(annotation,
                        squeeze_dims=[3])

    # 定义损失函数，这里使用交叉熵的平均值作为损失函数
    model_loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
                                                                                labels=labels,
                                                                                name="entropy")))
    model_loss_summary = tf.summary.scalar("model entropy", model_loss)

    tf.add_to_collection('losses', model_loss)
    loss = tf.add_n(tf.get_collection('losses'))  # including L2 losses

    loss_summary = tf.summary.scalar("total entropy", loss)
    # 定义优化器
    trainable_var = tf.trainable_variables()
    # for _ in trainable_var:
    #     print(_)

    if FLAGS.debug:
        for var in trainable_var:
            utils.add_to_regularization_and_summary(var)
    train_op = train(loss, trainable_var)

    # 加载数据集
    print("Setting up image reader...")

    train_records, valid_records = scene_parsing.read_dataset(FLAGS.data_dir, FLAGS.data_name)

    print("训练集的大小:", len(train_records))
    print("验证集的大小:", len(valid_records))

    print("Setting up dataset reader")

    image_options = {'resize': True, 'resize_size': FLAGS.IMAGE_SIZE}
    if FLAGS.mode == 'train':
        train_dataset_reader = dataset.BatchDatset(train_records, image_options)
    validation_dataset_reader = dataset.BatchDatset(valid_records, image_options)

    # 开始训练模型
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
    print("Setting up Saver...")
    saver = tf.train.Saver()

    # summary merging
    summary_merge = tf.summary.merge_all()

    # create two summary writers to show training loss and validation loss in the same graph
    # need to create two folders 'train' and 'validation' inside FLAGS.logs_dir
    train_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/train', sess.graph)
    validation_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/validation')

    sess.run(tf.global_variables_initializer())
    ckpt = tf.train.get_checkpoint_state(FLAGS.logs_dir)
    if ckpt and ckpt.model_checkpoint_path:
        saver.restore(sess, ckpt.model_checkpoint_path)
        print('model ' + ckpt.model_checkpoint_path.split('-')[-1] + ' restored...')

    start = 0
    if ckpt:
        start = ckpt.model_checkpoint_path.split('-')[-1]
        start = int(start) + 1

    # best valid
    best = 1e8  # set as infi

    if FLAGS.mode == "train":
        for itr in range(start, FLAGS.MAX_ITERATION):
            train_images, train_annotations, _ = train_dataset_reader.next_batch(FLAGS.batch_size)
            print(np.shape(train_images), np.shape(train_annotations))
            feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85}

            # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            # lo, ls, anno, lab = sess.run([loss, logits, pred_annotation, labels], feed_dict=feed_dict)
            # nan = np.sum(np.isnan(ls))
            # print('nan #', nan)
            # print('labels:', lab, 'unique', np.unique(lab))
            # print('ls', ls)
            # print('shape', ls.shape)
            # print('pred_annotation', anno)
            # print('loss', lo)
            # print('*' * 30)
            sess.run(train_op, feed_dict=feed_dict)
            print("step:", itr)

            if itr % 10 == 0:
                if FLAGS.debug:
                    train_loss, summary_str = sess.run([loss, summary_merge], feed_dict=feed_dict)
                else:
                    train_loss, summary_str = sess.run([loss, loss_summary], feed_dict=feed_dict)
                print("Step: %d, Train_loss:%g" % (itr, train_loss))
                train_writer.add_summary(summary_str, itr)

            if itr % 100 == 0:
                valid_images, valid_annotations, _ = validation_dataset_reader.next_batch(14)  # FLAGS.batch_size)
                valid_loss, summary_sva = sess.run([model_loss, model_loss_summary],
                                                   feed_dict={image: valid_images, annotation: valid_annotations,
                                                              keep_probability: 1.0})
                print("%s ---> Validation_loss: %g" % (datetime.datetime.now(), valid_loss))

                # add validation loss to TensorBoard
                validation_writer.add_summary(summary_sva, itr)

                # saver.save(sess, FLAGS.logs_dir + "model.ckpt", itr)

                if valid_loss < best:
                    best = valid_loss
                    # os.system('rm -f ./logs/best/*')
                    saver.save(sess, FLAGS.logs_dir + "best/" + "model.ckpt", itr)
    elif FLAGS.mode == "visualize":
        valid_images, valid_annotations, idx = validation_dataset_reader.next_batch(
            FLAGS.batch_size)  # get_random_batch(FLAGS.batch_size)

        # testing for any size
        # valid_images = np.expand_dims(valid_images[0], axis=0)
        # valid_annotations = np.expand_dims(valid_annotations[0], axis=0)
        # print(valid_images.shape)
        # print(valid_annotations.shape)
        pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations,
                                                    keep_probability: 1.0})
        valid_annotations = np.squeeze(valid_annotations, axis=3)
        pred = np.squeeze(pred, axis=3)
        for itr in range(FLAGS.batch_size):
            # utils.save_image(valid_images[itr].astype(np.uint8), FLAGS.logs_dir, name="inp_" + str(5 + itr))
            # utils.save_image(valid_annotations[itr].astype(np.uint8), FLAGS.logs_dir, name="gt_" + str(5 + itr))
            # utils.save_image(pred[itr].astype(np.uint8), FLAGS.logs_dir, name="pred_" + str(5 + itr))
            valid_image = valid_images[itr].astype(np.uint8)
            utils.save_image(valid_image, FLAGS.logs_dir, name="inp_" + idx[itr])

            predone = pred[itr].astype(np.uint8)
            img_rgb = utils.color_transform(predone, FLAGS.NUM_OF_CLASSES)
            utils.save_image(img_rgb.astype(np.uint8), FLAGS.logs_dir, name="pred_color_" + idx[itr])

            dst = utils.sobel(cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY))
            edgedImage = utils.draw_edge(dst, valid_image)
            utils.save_image(edgedImage.astype(np.uint8), FLAGS.logs_dir, name="pred_" + idx[itr])
            print("Saved image: %d" % itr)

    train_writer.close()
    validation_writer.close()
    sess.close()

if __name__ == "__main__":
    tf.app.run()


import csv
import os
import searchwordApi
import download
import time
import playsound

mp3path = r'second2/'

writefile=open('english.csv','w',newline='',encoding='utf-8')
writecsv=csv.writer(writefile)

with open('eng.csv',encoding='utf-8') as englishFile:
    englishReader = csv.reader(englishFile)

    for i in englishReader:
        line=i
        print(str(englishReader.line_num) + str(i[5]))
        if str(i[6])=="1":
            word= str(i[5])
            filename=mp3path+str(i[5])+'.mp3'
            wordmean=searchwordApi.getwordMean(word)
            if wordmean['mean']=='error':
                print(word+' is not found !')
                wordmean['mean']=''
        else:
            wordmean['mean']=''

            #print(wordmean['mean'][0])
        line.append(wordmean['mean'])
        writecsv.writerow(line)

        """
        if len(wordmean['us_mp3'])<1:
            download.downloadfile(wordmean['en_mp3'],filename)
        else:
            download.downloadfile(wordmean['us_mp3'],filename)
        """

            #playsound.playsound(filename, True)
writefile.close()


import tensorflow as tf
from tensorflow.contrib import slim

from nets import inception
from tensorflow.python.framework.graph_util import convert_variables_to_constants
from tensorflow.python.tools.optimize_for_inference_lib import optimize_for_inference
from preprocessing import inception_preprocessing

checkpoints_dir = '/home/navallo/Documents/DATA/flowers/log/all/'
OUTPUT_PB_FILENAME = '/home/navallo/Documents/CODE/20170327so/minimal_graph.proto'
NUM_CLASSES = 250

# We need default size of image for a particular network.
# The network was trained on images of that size -- so we
# resize input image later in the code.
image_size = inception.inception_resnet_v2.default_image_size

with tf.Graph().as_default():
    # Inject placeholder into the graph
    input_image_t = tf.placeholder(tf.string, name='input_image')
    image = tf.image.decode_jpeg(input_image_t, channels=3)

    # Resize the input image, preserving the aspect ratio
    # and make a central crop of the resulted image.
    # The crop will be of the size of the default image size of
    # the network.
    # I use the "preprocess_for_eval()" method instead of "inception_preprocessing()"
    # because the latter crops all images to the center by 85% at
    # prediction time (training=False).
    processed_image = inception_preprocessing.preprocess_for_eval(image,
                                                                  image_size,
                                                                  image_size, central_fraction=None)

    # Networks accept images in batches.
    # The first dimension usually represents the batch size.
    # In our case the batch size is one.
    processed_images = tf.expand_dims(processed_image, 0)

    # Load the inception network structure
    with slim.arg_scope(inception.inception_resnet_v2_arg_scope()):
        logits, _ = inception.inception_resnet_v2(processed_images,
                                                  num_classes=NUM_CLASSES,
                                                  is_training=False)
    # Apply softmax function to the logits (output of the last layer of the network)
    probabilities = tf.nn.softmax(logits)

    model_path = tf.train.latest_checkpoint(checkpoints_dir)

    # Get the function that initializes the network structure (its variables) with
    # the trained values contained in the checkpoint
    init_fn = slim.assign_from_checkpoint_fn(
        model_path,
        slim.get_model_variables())

    with tf.Session() as sess:
        # Now call the initialization function within the session
        init_fn(sess)

        # Convert variables to constants and make sure the placeholder input_image is included
        # in the graph as well as the other neccesary tensors.
        constant_graph = convert_variables_to_constants(sess, sess.graph_def, ["input_image", "DecodeJpeg",
                                                                               "InceptionResnetV2/Logits/Predictions"])

        # Define the input and output layer properly
        optimized_constant_graph = optimize_for_inference(constant_graph, ["eval_image"],
                                                          ["InceptionResnetV2/Logits/Predictions"],
                                                          tf.string.as_datatype_enum)
        # Write the production ready graph to file.
        tf.train.write_graph(optimized_constant_graph, '.', OUTPUT_PB_FILENAME, as_text=False)


import pandas as pd

df = pd.read_csv('KHP_test.csv')

# in this case, the reactant is named by XSASRUDTFFBDDK
RE = float(df[df.name=='XSASRUDTFFBDDK']['pred_SPE'].item())

# compute the activation energies
for i in range(len(df)):
    TS = df.iloc[i]
    if TS['name'] == 'XSASRUDTFFBDDK': continue
    print("Activation energy of {} is {:< 5.2f} kcal/mol".format(TS['name'], 627.5*(TS.pred_SPE-RE)))


'''CRUD operations'''
import os
import pymongo
from p1.user.model import User, Applicant
from p1.data.logger import get_logger
from p1.operations.las import Las
import datetime

log = get_logger(__name__)
las = Las()

try:
    client = pymongo.MongoClient(os.environ.get('MONGO_URI'), ssl=True)
    _db = client['LAS']
except:
    log.exception('Could not connect to Mongo')
    raise
def _get_id():
    '''Retrieves the next id in the database and increments it.'''
    counter = _db.counter.find_one_and_update({'_id': 'UNIQUE_COUNT'},
                                            {'$inc': {'count': 1}},
                                            return_document=pymongo.ReturnDocument.AFTER)['count']
    return counter
def login(username, password):
    '''A function that takes in a username and returns a user object with that username'''
    query_dict = {'username': username}
    user_dict = _db.users.find_one(query_dict)
    if user_dict['password'] == password:
        return User.from_dict(user_dict) if user_dict else None
    else:
        return None
def signup(user_info):
    user = {}
    user['_id'] = _get_id()
    user['firstName'] = user_info[0]
    user['lastName'] = user_info[1]
    user['username'] = user_info[2]
    user['password'] = user_info[3]
    user['address'] = user_info[4]
    user['city'] = user_info[5]
    user['state'] = user_info[6]
    user['income'] = user_info[7]
    user['debt'] = user_info[8]
    user['expenses'] = user_info[9]
    user['user_type'] = 'customer'
    user['risk'] = las.get_risk(user['income'], user['debt'], user['expenses'])
    _db.users.insert_one(user)
def apply(application,user):
    '''Evaluates loan and sets it on database. Returns status of loan'''
    #query
    user_id = user['_id']
    id_query = {"_id": user_id}
    query = {'$push':{"loans": application}}
    _db.users.update_one(id_query, query)
def get_loans():
    query = { "loans": { '$exists': 'true' } }
    loan_list = []
    loan_list = [User.from_dict(user) for user in _db.users.find(query)]
    return loan_list
def actOnLoan(body):
    user_id = int(body.pop())
    loan_id = int(body.pop())
    status = body.pop()
    id_query = { "_id": user_id}
    user = _db.users.find_one(id_query)
    for loan in user['loans']:
        if loan['_id'] == loan_id:
            thisLoan = loan
    thisLoan['status'] = status
    query = {"_id": user_id}
    _db.users.replace_one(query, user)
    return user


"""
    Python code to print each character of the string "mumbai"
    and its Unicode code point and sum of these Unicode code points
    and to create a list that contains the Unicode code points of the characters in S using map class
"""

S = 'mumbai'

unicode_sum = 0

for char in S:
    print(f"Character: {char}, Unicode Code Point: {ord(char)}")

    unicode_sum += ord(char)

print(f"\nSum of Unicode Code Points: {unicode_sum}")

# creating a list using map class

unicode_map = list(map(ord, S))
print("\nUsing Map Class:", unicode_map)


from bs4 import BeautifulSoup
import requests
import cli_helper
import re
import urllib.parse

color = cli_helper.color()

def main():
    domain = r'http://audiobookbay.nl'
    search_prefix = r'/?s='
    user_search = input("Enter search term: ") # TODO: Error if no results

    # Create BeautifulSoup of the main page to get number of pages
    main_url = domain + search_prefix + user_search
    r = requests.get(main_url)
    soup = BeautifulSoup(r.content, 'html.parser')

    navigation = soup.select('.wp-pagenavi a')
    if len(navigation) > 0:
        navigation_last = str(navigation[len(navigation) - 1])
        navigation_secondLast = navigation[len(navigation) - 2].text.strip()
        # NOTE: navigation_last is the whole HTML element, and navigation_secondLast is only the text from the element
        # (number of pages as string)

        if "»»" in navigation_last:
            # Finds all the integers in given String
            maxPages = re.findall(r'\d+', navigation_last)[0]
            maxPages = int(maxPages)
            print(f"Number of pages found: {maxPages}")
        else:
            maxPages = int(navigation_secondLast)
            print(f"Number of pages found: {maxPages}")

        pages = [main_url]
        for i in range(2, maxPages + 1):
            pages.append(domain + r'/page/' + str(i) + search_prefix + user_search)
    else:
        pages = [main_url]
        print("Only 1 page found")
        print("")

    nth = 1
    post_link_list = []

    for page in pages:
        r = requests.get(page)
        soup = BeautifulSoup(r.content, 'html.parser')
        contents = soup.select('.post')

        for post in contents:
            # TODO: Breaks at second page of "ready player one" search for unknown reason (post re-ab class?)
            postTitle = post.select_one('.postTitle h2 a').text.strip()
            # TODO: Parse book language for postInfo
            # Named "raw" because the String at this point is not very readable
            rawPostContent = post.select('.postContent p')[3].text.strip()
            # TODO: rawPostContent doesn't acguire the file size if it's in Bytes instead of GBs
            postContent = formatContent(rawPostContent)
            postLink = domain + post.select_one('.postTitle h2 a')['href']

            print(color.BOLD + color.UNDERLINE +
                  str(nth) + ". " + postTitle + color.END)
            print(postContent)
            print("")  # Puts empty line between books

            # Puts post link to list so user can later retrieve it)
            # TODO: Doesn't work, first variable is put on slot 0 etc... see 'choice' variable below
            post_link_list.insert(nth, postLink)
            nth += 1

        choice = input("Type 'y' to show next page, or select audiobook by its number: ") #  DISABLED FOR FASTER TESTING
        # choice = "0"
        print("")  # Empty line for better formatting

        if choice is not "y":  # TODO: Better choice checking;, continue if choice is anything but integer?
            break
        # TODO: Crashes if you go to unexisting page

    # ### PARSING THE BOOK PAGE FROM HERE BELOW ### #

    post_url = post_link_list[int(choice) - 1]
    r = requests.get(post_url)
    soup = BeautifulSoup(r.content, 'html.parser')

    name = soup.select_one('.postTitle h1').text.strip()

    data = []  # The table from book's page
    base_table = soup.select_one('.torrent_info')
    rows = base_table.find_all('tr')
    for row in rows:  # Goes through the table and creates simpler list
        cols = []
        cols_raw = row.find_all('td')
        for col in cols_raw:
            cols.append(col.get_text())
        data.append(cols)

    trackers = []  # TODO: Find out which trackers abb uses
    # Go throught the table to extract all needed information
    for row in data:
        if row[0] == "Tracker:":
            trackers.append(row[1])
        if row[0] == "Info Hash:":
            hash = row[1]

    print(color.BOLD + color.UNDERLINE + name + color.END)
    print("")

    magnet_link = generateMagnet(name, hash, trackers)
    print(magnet_link)

def formatContent(s):
    formatted = s.replace("Format:", " / Format:")
    formatted = formatted.replace("  /", " /")
    formatted = formatted.replace("File ", "/ File ")
    formatted = formatted.replace("Kbps/", "Kbps /")
    formatted = formatted.replace("?/", "? /")
    formatted = formatted.replace("?", color.RED + "?" + color.END)
    return formatted

def generateMagnet(name, hash, trackers):
    prefix = 'magnet:?xt=urn:btih:'
    beforeTitle = '&dn='
    title = urllib.parse.quote(name)
    encoded_trackers = []
    final = prefix + hash + beforeTitle + title
    for tracker in trackers:
        tracker = urllib.parse.quote(tracker)
        tracker = tracker.replace("/", "%2F")
        tracker = "&tr=" + tracker
        # encoded_trackers.append(tracker)
        final = final + tracker
    return final

main()


import scraper
import threading
import requests
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
listings = []
listingIDs = []

def pushover(title, message):
    print("sending notif")
    r = requests.post("https://api.pushover.net/1/messages.json", data = {
        "token": config.get('pushover', 'token'),
        "user":config.get('pushover', 'user'),
        "title": title,
        "message": message,
    })

def scrapeListings():
    threading.Timer(1800.0, scrapeListings).start()
    scrape = scraper.MartplaatsScrapper()
    if not listings:
        pushover("Starting marktplaats scraper", "The scraper will now check for new listings every 30 minutes")
        for listing in scrape:
            listings.append(listing)
            listingIDs.append(listing["mID"])
    else:
        for listing in scrape:
            if(listing["mID"] not in listingIDs):
                listings.append(listing)
                listingIDs.append(listing["mID"])
                message = (listing["price"] + " - " + listing["title"] + " " + listing["url"])
                pushover("New bike listing", message)

scrapeListings()


"""project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.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, include
from user import views as user_view
from django.contrib.auth import views as auth

from .router import router
from rest_framework.authtoken import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [

    path('admin/', admin.site.urls),

    ######### api path ##########################

    path('api/', include(router.urls)),
    path('api-token-auth/', views.obtain_auth_token, name='api-tokn-auth'),

    #####user related path##########################
    path('', include('user.urls')),

    path('Login/', user_view.Login, name='Login'),
    path('logout/', auth.LogoutView.as_view(template_name='user/login.html'), name='logout'),
    path('register/', user_view.register, name='register'),
    path('actionUrl/', user_view.actionUrl, name='actionUrl'),
    path('my_form/', user_view.my_form, name='my_form'),
    path('maindishes/', user_view.maindishes, name='maindishes'),
    path('RecipePagee/<int:pk>', user_view.RecipePagee, name='RecipePagee'),
    path('neww/', user_view.neww, name='neww'),
    path('Starters/', user_view.Starters, name='Starters'),
    path('Salads/', user_view.Salads, name='Salads'),
    path('Desserts/', user_view.Desserts, name='Desserts'),
    path('EmailSend/', user_view.EmailSend, name='EmailSend'),
    path('My_Recipe/', user_view.My_Recipe, name='My_Recipe'),
    path('my_form_edit/<int:pk>', user_view.my_form_edit, name='my_form_edit'),
    path('update/<int:pk>', user_view.update, name='update'),
    path('delete/<int:pk>', user_view.delete, name='delete'),
    path('NewIndex/', user_view.NewIndex, name='NewIndex'),
    path('NewIndex2/', user_view.NewIndex2, name='NewIndex2'),

]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from typing import List

from PyQt5.QtWidgets import QMessageBox
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
# Initialize Qt resources from file resources.py
from .mapTools.squareTool import SquareMapTool
from .mapTools.firstTool import circleDrawerMapTool
from qgis.core import QgsProject, QgsGeometry, QgsLayerTreeGroup, QgsCoordinateReferenceSystem, QgsLayerTreeLayer, QgsEditFormConfig

# Import the code for the DockWidget
from .mySelectionNewDock_dockwidget import mySelectionNewDockDockWidget
import os.path

from .lib.layers_utils import LayerInfo, create_layer_from_gpkg, create_node, set_node_visibility, set_style
from .lib.checker import Checker
from .lib.export import simple_export, simple_export_with_layout, export_with_predefined_layout

class mySelectionNewDock:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'mySelectionNewDock_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&mySelectionNewDock')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'mySelectionNewDock')
        self.toolbar.setObjectName(u'mySelectionNewDock')

        #print "** INITIALIZING mySelectionNewDock"

        self.pluginIsActive = False
        self.dockwidget = None
        self.layers = []
        self.selectedLayer = None
        self.mapTool = circleDrawerMapTool(iface.mapCanvas())
        self.rectangleDrawTool = SquareMapTool(iface.mapCanvas())

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('mySelectionNewDock', message)

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/mySelectionNewDock/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'selectionWidget'),
            callback=self.run,
            parent=self.iface.mainWindow())

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

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        print ("** CLOSING mySelectionNewDock")

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        self.dockwidget = None
        self.selectedLayer = None
        self.layers = []
        self.pluginIsActive = False

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        print("** UNLOAD mySelectionNewDock")

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&mySelectionNewDock'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

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

    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            print ("** STARTING mySelectionNewDock")

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = mySelectionNewDockDockWidget()

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.TopDockWidgetArea, self.dockwidget)
            self.layers = [lyr.name() for lyr in QgsProject.instance().mapLayers().values()]

            #self.selectedLayer = QgsProject.instance().mapLayersByName(self.layers[0])[0]  # устанавливаем при запуске

            # добавление с ключом
            # for id, layer in QgsProject.instance().mapLayers().items():
            #     self.dockwidget.comboBox.addItem(layer.name(), userData=id)
            #     self.dockwidget.comboBox.addItem((layer.name(), id))

            self.dockwidget.comboBox.addItems(self.layers)
            self.dockwidget.comboBox.currentIndexChanged.connect(self.onLayerChange)
            self.dockwidget.pushButton.clicked.connect(self.makeQuery)
            self.dockwidget.loadProject.clicked.connect(self.loadProject)
            self.dockwidget.drawPolygon.clicked.connect(self.rectangle_draw)
            self.dockwidget.checkParcel.clicked.connect(self.polygon_checker)
            self.dockwidget.simpleExport.clicked.connect(self.simple_print)
            self.dockwidget.show()

    def onLayerChange(self, index):

        # print(index)

        # Доступ по имени
        print(self.layers[index])
        # print(index)
        selectedLayerName = self.layers[index]
        self.selectedLayer = QgsProject.instance().mapLayersByName(selectedLayerName)[0]  # возвращает список

    def makeQuery(self):

        # Запрос
        print('Do query')

        # sF = []
        # sFeatures = self.selectedLayer.selectedFeatures()
        # if len(sFeatures) == 0:
        #     return
        # for f in sFeatures:
        #     sF.append(f.id())
        #
        # exp = ",".join([str(i) for i in sF])
        # print (f"fid in ({exp})")
        # self.selectedLayer.setSubsetString(f"fid in ({exp})")

        # Инструмент
        # set my cutom tool to qgis
        if not self.mapTool.isActive():
            self.iface.mapCanvas().setMapTool(self.mapTool)
        else:
            self.mapTool.clearRubberBand()
            self.iface.mapCanvas().unsetMapTool(self.mapTool)

    def loadProject(self):

        curFolder = os.path.dirname(os.path.abspath(__file__))
        base_map_GPKG = os.path.join(curFolder, "data", "basemap.gpkg")
        stylePath = os.path.join(curFolder, "style")
        crs = QgsCoordinateReferenceSystem("EPSG:32640")

        # Список слоев для проекта.
        # источник (GeoPackage), слой в источнике, имя в проекте, стиль, видимость слоя, имя группы
        layers_info: List[LayerInfo] = [
            LayerInfo(base_map_GPKG, "boundary", "Граница МО", "boundary.qml", True),
            LayerInfo(base_map_GPKG, "pk_boundary", "Граница ПК", "pk_boundary.qml", False),
        ]

        QgsProject.instance().setCrs(crs)

        for idx, layer in enumerate(layers_info):
            layerToAdd = create_layer_from_gpkg(base_map_GPKG, layer.src_layer, layer.node_name, crs)
            set_style(layerToAdd, layer.style, stylePath)
            QgsProject().instance().addMapLayer(layerToAdd, False)
            node: QgsLayerTreeLayer = QgsLayerTreeLayer(layerToAdd)
            set_node_visibility(node, layer.visible_in_project)

            if layer.src_layer == "boundary":
                formConfig: QgsEditFormConfig = layerToAdd.editFormConfig()
                formPath = os.path.join(curFolder, "editForms", "boundary.ui")
                formConfig.setUiForm(formPath)

                formConfig.setInitCodeSource(QgsEditFormConfig.CodeSourceFile)
                formConfig.setInitFilePath(os.path.join(curFolder, "editForms", "boundary.py"))
                formConfig.setInitFunction("open")
                layerToAdd.setEditFormConfig(formConfig)

            QgsProject().instance().layerTreeRoot().insertChildNode(idx, node)

    def rectangle_draw(self):
        # Инструмент
        # set my custom tool to qgis
        if not self.rectangleDrawTool.isActive():
            self.iface.mapCanvas().setMapTool(self.rectangleDrawTool)
        else:
            self.rectangleDrawTool.clearRubberBand()
            self.iface.mapCanvas().unsetMapTool(self.rectangleDrawTool)

    def polygon_checker(self):
        checker = Checker()
        if self.rectangleDrawTool.geometry:
            checker.check_geometry(self.rectangleDrawTool.geometry)
            QMessageBox.information(self.iface.mainWindow(), "Сообщение",
                                 u"Участок проверен")
        else:
            QMessageBox.critical(self.iface.mainWindow(), "Сообщение",
                                 u"Не установлена геометрия")

    def simple_print(self):
        # simple_export(self.iface.activeLayer())
        # simple_export_with_layout(self.iface)
        export_with_predefined_layout(self.iface)


# Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and
# routing e-mail between mail servers.
#
# Python provides smtplib module, which defines an SMTP client session object that
# can be used to send mail to any Internet machine with an SMTP or ESMTP listener
# daemon.
#
# Here is a simple syntax to create one SMTP object, which can later be used to send
# an e-mail:
#       import smtplib
#       smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
#
# Here is the detail of the parameters:
#    host: This is the host running your SMTP server. You can specify IP address of
#           the host or a domain name like tutorialspoint.com. This is optional argument.
#    port: If you are providing host argument, then you need to specify a port,
#           where SMTP server is listening. Usually this port would be 25.
#    local_hostname: If your SMTP server is running on your local machine, then
#           you can specify just localhost as of this option.
#
# An SMTP object has an instance method called sendmail, which is typically used to
# do the work of mailing a message. It takes three parameters:
#    The sender - A string with the address of the sender.
#    The receivers - A list of strings, one for each recipient.
#    The message - A message as a string formatted as specified in the various RFCs.
#

import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """
From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message)
    print("Successfully sent email")
except SMTPException:
    print("Error: unable to send email")


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

import numpy as np

import tensorflow as tf
from tensorflow import keras

from keras import Model
from keras.layers import Input
from keras import backend as K
from keras.models import load_model

from cv2 import cv2

from model import yolo_body, yolo_eval
from train import create_model

from utils import get_anchors, get_classes
from utils import letterbox_image, letterbox_frame

from path import path
from path import weight_path, classes_path, anchors_path, log_dir, json_path
from path import images_path
from path import font_path

from PIL import Image, ImageFont, ImageDraw
import colorsys

import os
import multiprocessing as mp
import time

def _main():
    # 显存分配
    gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
    for gpu in gpus:
        tf.config.experimental.set_memory_growth(gpu, True)

    # 屏蔽warning
    os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"

    # 加载模型
    model, model_param = load()
    class_names, num_classes, anchors, input_shape = model_param
    # model.summary()

    # 预测参数调整
    score = 0.3
    iou = 0.45

    # 获取分类框颜色
    colors = get_colors(num_classes)

    # 启动子进程
    frame_queue = mp.Queue()
    result_queue = mp.Queue()
    label_queue = mp.Queue()
    video_redad = mp.Process(target = opencv_process, args = (frame_queue, result_queue, label_queue))

    video_redad.start()

    while(True):
        if frame_queue.qsize() >= 1:
            frame = frame_queue.get()
        else:
            print('no video')
            frame = np.zeros([416, 416, 3])

        # 检测
        image_data, raw_image_shape = process_frame(frame, input_shape)
        res = detect(image_data, raw_image_shape, model, model_param, score, iou)

        if res != []:
            result_queue.put(res)

        if not label_queue.empty():
            if label_queue.get() == None:
                break

    while not label_queue.empty():
        label_queue.get()

    video_redad.join()

    print('Main process done')

def load():
    """
    加载模型，回传模型和模型参数
    """

    # 模型参数
    class_names = get_classes(classes_path)
    num_classes = len(class_names)

    anchors = get_anchors(anchors_path)
    num_anchors = len(anchors)

    input_shape = (416, 416)

    train_weights_path = log_dir + '/trained_weights_final.h5'

    # 获取模型结构，加载权重
    image_input = Input(shape=(None, None, 3))

    model = yolo_body(image_input, num_anchors//3, num_classes)
    print('Get YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))

    model.load_weights(train_weights_path, by_name=True, skip_mismatch=True)
    print('Load weights {}.'.format(train_weights_path))

    # 回传参数
    param = [class_names, num_classes, anchors, input_shape]

    return model, param

def process_image(img_path, input_shape):
    """
    将输入的图片处理成模型的标准输入形状
    """
    image = Image.open(img_path)
    image_shape = (image.width, image.height)

    # 改变image的形状
    if input_shape != (None, None):
        assert input_shape[0]%32 == 0, 'Multiples of 32 required'
        assert input_shape[1]%32 == 0, 'Multiples of 32 required'
        boxed_image = letterbox_image(image, tuple(reversed(input_shape)))
    else:
        new_image_size = (image.width - (image.width % 32),
                            image.height - (image.height % 32))
        boxed_image = letterbox_image(image, new_image_size)
    image_data = np.array(boxed_image, dtype='float32')

    # 归一化
    image_data /= 255.
    # Add batch dimension. (w, h, 3) -> (m, w, h, 3)
    image_data = np.expand_dims(image_data, 0)

    print(image_data.shape)

    return image_data, image_shape

def process_frame(frame, input_shape):
    """
    将输入的帧处理成模型的标准输入形状
    """
    image_width = frame.shape[0]
    image_hight = frame.shape[1]
    image_shape = (image_hight, image_width)

    if input_shape != (None, None):
        assert input_shape[0]%32 == 0, 'Multiples of 32 required'
        assert input_shape[1]%32 == 0, 'Multiples of 32 required'
        boxed_image = letterbox_frame(frame, tuple(reversed(input_shape)))
    else:
        new_image_size = (image_width - (image_width % 32),
                            image_hight - (image_hight % 32))
        boxed_image = letterbox_frame(frame, new_image_size)
    image_data = np.array(boxed_image, dtype='float32')

    # 归一化
    image_data /= 255.
    # Add batch dimension. (w, h, 3) -> (m, w, h, 3)
    image_data = np.expand_dims(image_data, 0)

    # print(image_data.shape)

    return image_data, image_shape

def get_colors(num_classes):
    # Generate colors for drawing bounding boxes.
    # 生成随机颜色列表，以对应不同的框
    hsv_tuples = [(x / num_classes, 1., 1.) for x in range(num_classes)]

    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
    colors = list(map(lambda x: (int(x[0] * 255),
                    int(x[1] * 255), int(x[2] * 255)),colors))

    np.random.seed(10101)  # Fixed seed for consistent colors across runs.
    np.random.shuffle(colors)  # Shuffle colors to decorrelate adjacent classes.
    np.random.seed(None)  # Reset seed to default

    return colors

def predict(data, image_shape,
            model, model_param,
            score_threshold = .6,
            iou_threshold = .5,
            max_boxes = 20):
    """
    yolo_eval:
    Evaluate YOLO model on given input and return filtered boxes.
    """

    class_names, num_classes, anchors, input_shape = model_param

    # data shape = [(1, 13, 13, 75), (1, 26, 26, 75), (1, 52, 52, 75)]
    grid1, grid2, grid3 = np.array(data[0]), np.array(data[1]), np.array(data[2])
    # print(grid1.shape, grid2.shape, grid3.shape)
    # print(grid1[0, 7, 5, :25])

    # predict

    boxes, scores, classes = yolo_eval(data, anchors,
                num_classes, image_shape,
                score_threshold=score_threshold, iou_threshold=iou_threshold)

    result = [boxes, scores, classes]
    return result

def output(image_shape, boxes, scores, classes, class_names):
    """
    processing output data
    """

    res = []

    for i, c in reversed(list(enumerate(classes))):
        predicted_class = class_names[c]
        box = boxes[i]
        score = scores[i]

        label = '{} {:.2f}'.format(predicted_class, score)

        '''
        识别框调整：
            纵向：数值增大，识别框向下移动
            横向：数值增大，识别框向右移动
        url：-300， 500
        视频：-200， 250
        紧急救援：-220， 200
        '''

        height_dv = -220
        width_dv = 200

        # height_dv = -300
        # width_dv = 500

        top, left, bottom, right = box
        top = max(0, np.floor(top + height_dv).astype('int32'))
        left = max(0, np.floor(left + width_dv).astype('int32'))
        bottom = min(image_shape[1], np.floor(bottom + height_dv).astype('int32'))
        right = min(image_shape[0], np.floor(right + width_dv).astype('int32'))

        res_single = [label, left, top, right, bottom]
        res.append(res_single)

    return res

def detect(image_data, raw_image_shape, model, model_param, score, iou):
    class_names, num_classes, anchors, input_shape = model_param

    # 预测
    data = model.predict(image_data)
    boxes, scores, classes = predict(data, raw_image_shape, model, model_param, score, iou)
    # print('Found {} boxes form {}'.format(len(boxes), 'img'))

    # 输出
    res = output(raw_image_shape, boxes, scores, classes, class_names)

    if res != []:
        print(res)

    return res

def opencv_process(frame_queue, result_queue, label_queue):
    # 视频流
    url = "rtsp://admin:tiyoa000@192.168.0.64/Streaming/Channels/1"
    cap = cv2.VideoCapture(url)

    cap = cv2.VideoCapture('/home/wyundi/Videos/190319222227698228.mp4')

    while(True):
        ret, frame = cap.read()

        # 调整帧率
        time.sleep(0.03)

        if frame_queue.qsize() < 2:
            frame_queue.put(frame)

        if not result_queue.empty():
            res = result_queue.get()

            for i in range(len(res)):
                label, left, top, right, bottom = res[i]
                cv2.rectangle(frame, (left, top), (right, bottom), (0,255,0), 3)

        cv2.namedWindow("capture", 0)
        # cv2.resizeWindow("capture", 1080, 640)    # 设置长和宽

        cv2.imshow('capture', frame)

        if cv2.waitKey(1) == ord('q'):
            label_queue.put(None)
            break

    cap.release()
    cv2.destroyAllWindows()

    while not frame_queue.empty():
        frame_queue.get()

    print('Sub process done')

if __name__ == '__main__':
    _main()


from .config import Configuration
import tweepy
import time

config = Configuration()

class Tweet:
    def __init__(self, account, nft_collection=None):
        self.account = account
        if self.account not in config.yaml_file['twitter']['sub_twitter']:
            pass

        if nft_collection is None:
            consumer_key = config.yaml_file['twitter']['sub_twitter'][account]['OAuthHandler']['consumer_key']
            consumer_sec = config.yaml_file['twitter']['sub_twitter'][account]['OAuthHandler']['consumer_secret']
            access_key = config.yaml_file['twitter']['sub_twitter'][account]['access_token']['key']
            access_sec = config.yaml_file['twitter']['sub_twitter'][account]['access_token']['secret']
        else:
            consumer_key = config.yaml_file['twitter']['collections'][nft_collection][account]['OAuthHandler']['consumer_key']
            consumer_sec = config.yaml_file['twitter']['collections'][nft_collection][account]['OAuthHandler']['consumer_secret']
            access_key = config.yaml_file['twitter']['collections'][nft_collection][account]['access_token']['key']
            access_sec = config.yaml_file['twitter']['collections'][nft_collection][account]['access_token']['secret']

        if not consumer_key:
            return

        self.authorize = tweepy.OAuthHandler(consumer_key, consumer_sec)
        self.authorize.set_access_token(access_key, access_sec)
        self.api = tweepy.API(self.authorize, wait_on_rate_limit=True)
        self.supported_types = ['jpg', 'png', 'gif', 'webp', 'mp3', 'mp4']
        self.client = tweepy.Client(consumer_key=consumer_key, consumer_secret=consumer_sec, access_token=access_key, access_token_secret=access_sec)

    def alert(self, message, filename=None, verbose=False):
        try:
            if message is None:
                return "You can't send a blank tweet!"

            if verbose:
                print(f"==== [ Tweepy input ] ======\n"
                      f"{message}\n")

            # only attach media if the filepath is provided and is a supported file type.
            # .jpg, .png, .gif, .mp3, .mp4
            if filename and filename.split('.')[1] in self.supported_types:
                media = self.api.media_upload(filename)
                self.client.create_tweet(text=message, media_ids=[media.media_id], user_auth=True)
                print("🐤 tweet successfully sent with media!")
                time.sleep(5)
            else:
                self.client.create_tweet(text=message, user_auth=True)
                print("🐤 tweet successfully sent!")
                time.sleep(5)

        except Exception as tweepy_err:
            if tweepy_err == "[{'code': 187, 'message': 'Status is a duplicate.'}]":
                pass
            else:
                print(f"An error has occurred with Tweepy: {tweepy_err}")

    def latest_tweet(self):
        return self.api.search_tweets(q="", count=1)


import sys
import csv

def main(input_file_name):
    head = "!TRNS,TRNSTYPE,DATE,ACCNT,MEMO,AMOUNT,CLASS\r\n!SPL,TRNSTYPE,DATE,ACCNT,MEMO,AMOUNT,CLASS\r\n!ENDTRNS,,,,,,"
    trans_start_template = "\nTRNS,GENJRN,{0},,,,"
    trans_body_template = "\nSPL,GENJRN,{0},{1},{2},{3},PAWNIT"
    trans_end_template = "\nENDTRNS,,,,,,"
    last_date_processed = None

    with open(input_file_name, 'r') as input_file:
        csv_reader = csv.DictReader(input_file)
        trans_num = 0

        for trans in csv_reader:
            trans_date = trans.get("glh_date").split(None, 1)[0]
            trans_account = trans.get("gld_acct_posted")
            trans_memo = trans.get("glh_reference")
            trans_amount = trans.get("gld_amt")

            if last_date_processed != trans_date:
                if last_date_processed is not None:
                    with open(f'general_ledger_{ trans_num }.iif', mode='a', newline='') as output_file:
                        output_file.write(trans_end_template)
                trans_num += 1
                with open(f'general_ledger_{ trans_num }.iif', mode='a', newline='') as output_file:
                    output_file.write(head)
                    output_file.write(trans_start_template.format(trans_date))
                    output_file.write(trans_body_template.format(trans_date, trans_account, trans_memo, trans_amount))
                    last_date_processed = trans_date
            elif last_date_processed == trans_date:
                with open(f'general_ledger_{ trans_num }.iif', mode='a', newline='') as output_file:
                    output_file.write(trans_body_template.format(trans_date, trans_account, trans_memo, trans_amount))
        with open(f'general_ledger_{ trans_num }.iif', mode='a', newline='') as output_file:
            output_file.write(trans_end_template)

if __name__ == '__main__':
    if len(sys.argv) > 2:
        print('Only one argument is allowed.\nProvide only the file name to be cleaned as the argument.')
    elif len(sys.argv) <= 1:
        print('The file name to be cleaned is required as an argument.')
    else:
        try:
            main(sys.argv[1])
            print('The provided CSV file has been converted into multiple .iif files based on the transaction date.  '
                  'Please verify that all data is correct before importing into Quickbooks.')
        except FileNotFoundError:
            print(f'No file with the name: "{ sys.argv[1] }".  Please check the name and try again.')


from gevent import spawn, sleep, kill
from rooms.update import *
from rooms.models import *
import random
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect
from rooms.queue import json_response
import time
from gevent.event import Event

class RoomUpdate(object):
    def __init__(self, room):
        self.room_id = room.id
        self.timestamp = int(time.time())

class AvailManager(object):
    SIM_RUNNING = False
    sim_thread = None

    def __init__(self):
        self.updates = []
        self.event = Event()

    def run_sim(self, delay, size):
        roomids = Room.objects.filter(avail=True).values_list('id',flat=True)
        #print 'Room ids: %s ' % roomids
        ids = []
        for i in range(0, len(roomids)):
            ids.append(roomids[i])
            random.shuffle(ids)
        for i in range(0, len(ids)):
            roomg = Room.objects.filter(id=ids[i])
            updateavail(Room.objects.filter(id=ids[i]))
            room = roomg[0]
            self.updates.append(RoomUpdate(room))
            self.event.set()
            self.event.clear()
            if i % size == 0:
                sleep(delay)
        self.SIM_RUNNING = False

    def start_sim(self, delay, size=1):
        if self.SIM_RUNNING:
            kill(self.sim_thread)
        self.updates = []
        Room.objects.all().update(avail=True)
        self.sim_thread = spawn(self.run_sim, delay=delay, size=size)
        self.SIM_RUNNING = True
        return HttpResponse('Started Simulation with delay %d' % delay)

    def stop_sim(self):
        if not self.SIM_RUNNING:
            return HttpResponse('No current simulation')
        kill(self.sim_thread)
        self.SIM_RUNNING = False
        return HttpResponse('Stopped simulation')

    def check_avail(self, timestamp):
        if len(self.updates) == 0 or timestamp > self.updates[0].timestamp:
            self.event.wait()
        room_ids = []
        i = len(self.updates) - 1
        while i >= 0:
            i = i - 1
            update = self.updates[i]
            if timestamp <= update.timestamp:
                room_ids.append(update.room_id)
            else:
                break

        return json_response({'timestamp':int(time.time()),
                              'rooms':room_ids})

avail_manager = AvailManager()
start_sim = avail_manager.start_sim
stop_sim = avail_manager.stop_sim
check_avail = avail_manager.check_avail


import pandas as pd
import numpy as np
from scipy.stats import norm
from matplotlib import pyplot as plt
from scipy.stats import skew

data = pd.read_csv('data.csv')
data_array = np.genfromtxt("data.csv", delimiter=";", skip_header=1)
data_array.sort()
print(data_array)
length=len(data_array)
print('length:',length)
data=data_array
mu1 = np.mean(data)
std1 = np.std(data)
median1=np.median(data)
var1=np.var(data)
co_of_var=std1/mu1
skew1=skew(data)

print('mu1',mu1)
print('standard deviation1',std1)
print('median1',median1)
print('variance1',var1)
print('co efficient of variation',co_of_var)
print('skewness',skew1)

mu, std = norm.fit(data)
print('mu',mu)
print('standard deviation',std1)
pts=data
num_bins = 30
count, bins, ignored = plt.hist(pts, num_bins, density=True,
                                edgecolor='k')
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)
q = norm.pdf(x, mu1, std1)
plt.plot(x, p, 'g', linewidth=4)
plt.plot(x, q, 'r', linewidth=1)
title = "Fit results: mu = %.5f,  std = %.5f" % (mu, std)
plt.title(title)

plt.xlabel(r'service time')
plt.ylabel(r'number of occurremce')
plt.show()