"""
Calculate your water bill based on tier pricing
"""

def tier_water_bill():
    """My main function driver
    """
    # Task 1: Basic Water Usage
    # Take user input for the number of gallons of water used in a household
    gallons_usage = int(input('How many gallons you used this month? '))

    charge_tier1 = charge_tier2 = charge_tier3 = 0.00
    gallons_tier1 = gallons_tier2 = gallons_tier3 = 0
    # Basic, minimum charge
    if gallons_usage <= 2000:
        charge_tier1 = 30.00
        gallons_tier1 = gallons_usage
    else:
        # Tier 2: 2001 - 5000 gallons
        # Gallons in this range are charged at $0.08 per gallon
        if gallons_usage > 2000 and gallons_usage <= 5000:
            # Tier 1: 2000 gallons
            charge_tier1 = 30.00
            gallons_tier1 = 2000
            # Tier 2: 2001 - 5000 gallons
            gallons_tier2 = gallons_usage - gallons_tier1
            charge_tier2 = gallons_tier2 * 0.08
        # Tier 3: more than 5000 gallons
        # Gallons in this range are charged at $0.20 per gallon
        else:
            # Tier 1: 2000 gallons
            charge_tier1 = 30.00
            gallons_tier1 = 2000
            # Tier 2: 2001 - 5000 gallons
            gallons_tier2 = 3000
            charge_tier2 = gallons_tier2 * 0.08
            # Tier 3: more than 5000 gallons
            gallons_tier3 = gallons_usage - (gallons_tier1 + gallons_tier2)
            charge_tier3 = gallons_tier3 * 0.20

    final_charge = charge_tier1 + charge_tier2 + charge_tier3
    print(f'You used {gallons_usage} gallons, your bill is ${final_charge:.2f}')
    print(f'Tier1 (0-2000): {gallons_tier1} gallons,  ${charge_tier1:.2f}')
    print(f'Tier2 (2001-5000): {gallons_tier2} gallons,  ${charge_tier2:.2f}')
    print(f'Tier3 (more than 5000): {gallons_tier3} gallons,  ${charge_tier3:.2f}')

if __name__ == '__main__':
    tier_water_bill()


from .models import Auction
from .serializer import AuctionSerializer
from utils.utils import Utils
from django.db import connection

class AuctionService:

    def create(self, auction):
        serializer = AuctionSerializer(data=auction)

        if serializer.is_valid():
            serializer.save()
            return True

        return False

    def isNotEmpty(self):
        return Auction.objects.all().first()

    def deleteOldAuctions(self):
        cursor = connection.cursor()
        cursor.execute("DELETE FROM %s WHERE `isActive`=0" % Auction._meta.db_table)
        cursor.execute("OPTIMIZE TABLE %s" % Auction._meta.db_table)

    def getConnectedRealmActiveAucCount(self, connected_realm):
        count = 0
        for realm in connected_realm:
            count += Auction.objects.filter(ownerRealm=realm.name, isActive=1).count()
        return count

    def getActiveAuctions(self, connected_realms):
        current_auctions = []
        current_auctions_auc = {}

        for connected_realm in connected_realms:
            current_auctions += Auction.objects.filter(ownerRealm=connected_realm['name'], isActive=1)
        counter = 0
        for current_auction in current_auctions:
            counter += 1
            current_auctions_auc[current_auction.auc] = current_auction
        return current_auctions_auc

    def getRealmPriceList(self, _itemId, _realm_name):
        price_tab = []
        current_auctions = Auction.objects.filter(ownerRealm=_realm_name, isActive=1, item=_itemId)
        for current_auction in current_auctions:
            quantity = current_auction.quantity
            price = Utils.unifyPrice(current_auction.buyout)/quantity
            # If price == 0 then auction is only for bid
            if price > 0:
                while quantity > 0:
                    price_tab.append(price)
                    quantity -= 1
        return price_tab

    def getAllRealmActiveAuctionsList(self, _realm_name):
        return Auction.objects.filter(ownerRealm=_realm_name, isActive=1)

    def getCurrentAuctions(self, connected_realms):
        current_auctions = []
        current_auctions_auc = []

        for connected_realm in connected_realms:
            current_auctions += Auction.objects.filter(ownerRealm=connected_realm['name'], isActive=1)
        counter = 0
        for current_auction in current_auctions:
            counter += 1
            current_auctions_auc.append(current_auction.auc)
        return current_auctions_auc

    def unactive(self, _connected_realms, _auc):
        for connected_realm in _connected_realms:
            auction = Auction.objects.filter(ownerRealm=connected_realm['name'], auc=_auc).first()

            if auction:
                auction.isActive = False
                auction.save()
                return True

        return False

    def updateAuction(self, _auc):
        auction = Auction.objects.filter(ownerRealm=_auc['ownerRealm'],
                                         auc=_auc['auc']).first()
        if auction:
            if str(auction.bid) != str(_auc['bid']) or str(auction.buyout) != str(_auc['buyout']) or str(auction.quantity) != str(_auc['quantity']) or str(auction.timeLeft) != str(_auc['timeLeft']):
                auction.bid = _auc['bid']
                auction.buyout = _auc['buyout']
                auction.quantity = _auc['quantity']
                auction.timeLeft = _auc['timeLeft']
                auction.save()
                return True

        return False


import _
import config
from logging import Logger
from sklearn.metrics import *
from utils.experiments_utils import *
from utils.experiments_utils.results.tables import *
from utils.helpers.datasets import Dataset
from utils.rulekit.classification import RuleClassifier
from steps.train import TrainedModelsResults

def reduce_mean(df: pd.DataFrame) -> pd.DataFrame:
    numerical_columns = df.select_dtypes('number').columns.tolist()
    data = {}
    for column in df.columns.tolist():
        if column in numerical_columns and '(std)' not in column:
            data[column] = [df[column].mean()]
            data[f'{column} (std)'] = [df[column].std()]
        else:
            data[column] = [df[column].iloc[0]]
    return pd.DataFrame(data)

def write_rules(
    results_dir: str,
    models: TrainedModelsResults
):
    models = getattr(models, 'original')
    for i, model in enumerate(models):
        results_cv_dir = f'{results_dir}/original/cv/{i + 1}'
        os.makedirs(results_cv_dir, exist_ok=True)
        rule_file_path = f'{results_cv_dir}/rules.txt'
        with open(rule_file_path, 'w+') as file:
            for rule in model.model.rules:
                file.write(
                    f'{str(rule)} (p={int(rule.weighted_p)}, n={int(rule.weighted_n)}, P={int(rule.weighted_P)}, N={int(rule.weighted_N)})\n')

def evaluate_models(
    dataset: Dataset,
    variant_name: str,
    dataset_type: str,
    models: List[RuleClassifier],
    logger: Logger
) -> None:
    logger.info(
        f'Evalute model for dataset: "{dataset.name}" ({dataset_type}) for variant: "{variant_name}"')
    metrics: Table = Tables.get(dataset.name, variant_name, dataset_type, 'metrics')
    conditions_stats: Table = Tables.get(
        dataset.name, variant_name, dataset_type, 'conditions_stats')
    confusion_matrix_train_avg = None
    confusion_matrix_test_avg = None

    for i, model in enumerate(models):
        if len(models) == 1:
            logger.info(f'Evaluate on train_test')
            X_train, y_train, X_test, y_test = dataset.get_train_test()
        else:
            logger.info(f'Evaluate for fold: {i + 1}')
            X_train, y_train, X_test, y_test = dataset.get_cv_fold(i + 1)

        fold_metrics: Table = Tables.get(
            dataset.name, variant_name, dataset_type, 'cv', str(i + 1), 'metrics')

        prediction_test = model.predict(X_test)
        prediction_train = model.predict(X_train)

        fold_metrics.rows.append({
            'dataset': dataset.name,
            'variant': variant_name,
            'dataset type': dataset_type,

            'BAcc (test)': balanced_accuracy_score(y_test, prediction_test),
            'BAcc (train)': balanced_accuracy_score(y_train, prediction_train),
            'Acc (test)': accuracy_score(y_test, prediction_test),
            'Acc (train)': accuracy_score(y_train, prediction_train),
            'rules':  sum([
                value if 'statistics' not in key else 0 for key, value in model.model.stats.conditions_stats.stats.items()
            ]), # change conditiosn counting so that alternatives are counted as one conditions
            'conditions_count': model.model.stats.rules_count * model.model.stats.conditions_per_rule,
            'avg conditions per rule': model.model.stats.conditions_per_rule,
            'avg rule quality': model.model.stats.avg_rule_quality,
            'avg rule precision': model.model.stats.avg_rule_precision,
            'avg rule coverage': model.model.stats.avg_rule_coverage,
            'training time total (s)': model.model.stats.time_total_s,
            'training time growing (s)': model.model.stats.time_growing_s,
            'training time pruning (s)': model.model.stats.time_pruning_s,

            'induction measure': model.get_params()['induction_measure'].replace('Measures.', ''),
            'pruning measure': model.get_params()['pruning_measure'].replace('Measures.', ''),
            'voting measure': model.get_params()['voting_measure'].replace('Measures.', ''),
        })
        fold_metrics.save()

        labels_values = Dataset(dataset.name).get_full()[1].unique().tolist()
        cm = confusion_matrix(
            y_train, prediction_train, labels=labels_values)
        if confusion_matrix_train_avg is None:
            confusion_matrix_train_avg = cm
        else:
            confusion_matrix_train_avg += cm
        train_confusion_matrix = pd.DataFrame(
            cm,
            index=[f'true:{value}' for value in labels_values],
            columns=[f'pred:{value}' for value in labels_values]
        )
        train_confusion_matrix.to_csv(
            f'{os.path.dirname(fold_metrics._file_path)}/confusion_matrix_train.csv')

        cm = confusion_matrix(
            y_test, prediction_test, labels=labels_values)
        if confusion_matrix_test_avg is None:
            confusion_matrix_test_avg = cm
        else:
            confusion_matrix_test_avg += cm
        test_confusion_matrix = pd.DataFrame(
            cm,
            index=[f'true:{value}' for value in labels_values],
            columns=[f'pred:{value}' for value in labels_values]
        )
        test_confusion_matrix.to_csv(
            f'{os.path.dirname(fold_metrics._file_path)}/confusion_matrix_test.csv')

        fold_conditions_stats: Table = Tables.get(
            dataset.name, variant_name, dataset_type, 'cv', str(i + 1), 'conditions_stats')

        conditions_stats_dict: dict = model.model.stats.conditions_stats.stats
        conditions_stats_dict['dataset'] = dataset.name
        conditions_stats_dict['variant'] = variant_name
        conditions_stats_dict['dataset type'] = dataset_type
        tmp = conditions_stats_dict
        if 'Inner alternatives statistics' in conditions_stats_dict:
            for key, value in conditions_stats_dict['Inner alternatives statistics'].items():
                tmp[f'Inner alternatives - {key}'] = value
            del conditions_stats_dict['Inner alternatives statistics']
        fold_conditions_stats.rows.append(conditions_stats_dict)
        fold_conditions_stats.save()

        metrics.rows += fold_metrics.rows
        conditions_stats.rows += fold_conditions_stats.rows

    confusion_matrix_train_avg = confusion_matrix_train_avg / len(models)
    confusion_matrix_train_avg = pd.DataFrame(
        confusion_matrix_train_avg,
        index=[f'true:{value}' for value in labels_values],
        columns=[f'pred:{value}' for value in labels_values]
    )
    confusion_matrix_train_avg.to_csv(
        f'{os.path.dirname(metrics._file_path)}/confusion_matrix_train.csv')

    confusion_matrix_test_avg = confusion_matrix_test_avg / len(models)
    confusion_matrix_test_avg = pd.DataFrame(
        confusion_matrix_test_avg,
        index=[f'true:{value}' for value in labels_values],
        columns=[f'pred:{value}' for value in labels_values]
    )
    confusion_matrix_test_avg.to_csv(
        f'{os.path.dirname(metrics._file_path)}/confusion_matrix_test.csv')

    metrics.set_df(reduce_mean(metrics.as_pandas()))
    conditions_stats.set_df(reduce_mean(conditions_stats.as_pandas()))

def evaluate_all_models(
    dataset_name: str,
    variant_name: str,
    models: TrainedModelsResults,
    logger: Logger
) -> None:
    logger.info(
        f'Evalute model for dataset: "{dataset_name}" for variant: "{variant_name}"')
    Tables.configure(directory=config.RESULTS_BASE_PATH)

    logger.info('Write model rules')
    write_rules(
        f'{config.RESULTS_BASE_PATH}/{dataset_name}/{variant_name}', models)
    if len(models.original) > 0:
        dataset = Dataset(dataset_name)
        evaluate_models(dataset, variant_name, 'original',
                        models.original, logger)

@step()
def evaluate_plain_model(
    dataset_name: str,
    variant_name: str,
    models: TrainedModelsResults,
):
    evaluate_all_models(dataset_name, variant_name, models,
                        evaluate_plain_model.logger)

@step()
def evaluate_models_inner_alternatives(
    dataset_name: str,
    variant_name: str,
    models: TrainedModelsResults,
):
    evaluate_all_models(dataset_name, variant_name, models,
                        evaluate_models_inner_alternatives.logger)

@step()
def evaluate_models_complex_conditions(
    dataset_name: str,
    variant_name: str,
    models: TrainedModelsResults,
):
    evaluate_all_models(dataset_name, variant_name, models,
                        evaluate_models_complex_conditions.logger)

@step()
def evaluate_models_complex_conditions_and_alternatives(
    dataset_name: str,
    variant_name: str,
    models: TrainedModelsResults,
):
    evaluate_all_models(dataset_name, variant_name, models,
                        evaluate_models_complex_conditions_and_alternatives.logger)


T = int(input())

def dfs(x, y):
    global result
    graph[x][y] = 1
    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]
        if (0 <= nx < N) and (0 <= ny < N):
            if graph[nx][ny] == 0:
                dfs(nx, ny)
            if graph[nx][ny] == 3:
                result = 1
                return

for test_case in range(1, T+1):
    N = int(input())    # 미로의 크기 입력
    graph = [list(map(int ,input())) for _ in range(N)]    # 그래프 초기화, 리스트로 변환 숫자 쪼개기 위해
    # visited = [[False for _ in range(N)] for _ in range(N)]    # 방문체크
    # 상하좌우
    dx = [-1,1,0,0]
    dy = [0,0,-1,1]

    # start 지점 찾기 (숫자 2)
    for i in range(N):  # for 연산 한번 줄일수 있다.
        if 2 in graph[i]:
            x = i # 행
            y = graph[i].index(2)  # 열

    result = 0
    dfs(x, y)

    print("#%d %d" %(test_case, result))


import unittest
import torch
import numpy as np

import onnx
from onnx import helper
from onnx.helper import make_tensor_value_info, make_sequence_value_info
from functools import reduce

from interp.interp_utils import AbstractionInitConfig
from interp.interp_operator import Abstraction, Interpreter

from tests.test_abstraction import tf_equal, correct_abstraction

class TestAbstraction(unittest.TestCase):

    def abst_shape_check(self, obj: Abstraction):
        target_size = [len(x) for x in obj.splits]
        self.assertEqual(obj.get_dim(), len(obj.splits))
        self.assertEqual(obj.lb.dim(), obj.get_dim())
        self.assertEqual(obj.ub.dim(), obj.get_dim())
        self.assertEqual(obj.lb.shape, torch.Size(target_size))
        self.assertEqual(obj.ub.shape, torch.Size(target_size))

    def test_loop_11(self):
        # case loop_11 from https://github.com/onnx/onnx/blob/master/docs/Operators.md#Loop

        # Given a tensor x of values [x1, ..., xN], and initial tensor y
        # sum up its elements using a scan
        # returning the final state (y+x1+x2+...+xN) as well the scan_output
        # [y+x1, y+x1+x2, ..., y+x1+x2+...+xN]

        y_in = onnx.helper.make_tensor_value_info('y_in', onnx.TensorProto.FLOAT, [1])
        y_out = onnx.helper.make_tensor_value_info('y_out', onnx.TensorProto.FLOAT, [1])
        scan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [1])
        cond_in = onnx.helper.make_tensor_value_info('cond_in', onnx.TensorProto.BOOL, [])
        cond_out = onnx.helper.make_tensor_value_info('cond_out', onnx.TensorProto.BOOL, [])
        iter_count = onnx.helper.make_tensor_value_info('iter_count', onnx.TensorProto.INT64, [])

        x = np.array([1, 2, 3, 4, 5]).astype(np.float32)
        y = np.array([-2]).astype(np.float32)

        x_const_node = onnx.helper.make_node(
            'Constant',
            inputs=[],
            outputs=['x'],
            value=onnx.helper.make_tensor(
                name='const_tensor_x',
                data_type=onnx.TensorProto.FLOAT,
                dims=x.shape,
                vals=x.flatten().astype(float),
            )
        )

        one_const_node = onnx.helper.make_node(
            'Constant',
            inputs=[],
            outputs=['one'],
            value=onnx.helper.make_tensor(
                name='const_tensor_one',
                data_type=onnx.TensorProto.INT64,
                dims=(),
                vals=[1]
            )
        )

        i_add_node = onnx.helper.make_node(
            'Add',
            inputs=['iter_count', 'one'],
            outputs=['end']
        )

        start_unsqueeze_node = onnx.helper.make_node(
            'Unsqueeze',
            inputs=['iter_count'],
            outputs=['slice_start'],
            axes=[0]
        )

        end_unsqueeze_node = onnx.helper.make_node(
            'Unsqueeze',
            inputs=['end'],
            outputs=['slice_end'],
            axes=[0]
        )

        slice_node = onnx.helper.make_node(
            'Slice',
            inputs=['x', 'slice_start', 'slice_end'],
            outputs=['slice_out']
        )

        y_add_node = onnx.helper.make_node(
            'Add',
            inputs=['y_in', 'slice_out'],
            outputs=['y_out']
        )

        identity_node = onnx.helper.make_node(
            'Identity',
            inputs=['cond_in'],
            outputs=['cond_out']
        )

        scan_identity_node = onnx.helper.make_node(
            'Identity',
            inputs=['y_out'],
            outputs=['scan_out']
        )

        loop_body = onnx.helper.make_graph(
            [identity_node, x_const_node, one_const_node, i_add_node,
             start_unsqueeze_node, end_unsqueeze_node, slice_node, y_add_node,
             scan_identity_node],
            'loop_body',
            [iter_count, cond_in, y_in],
            [cond_out, y_out, scan_out]
        )

        node = onnx.helper.make_node(
            'Loop',
            inputs=['trip_count', 'cond', 'y'],
            outputs=['res_y', 'res_scan'],
            body=loop_body
        )

        trip_count = np.array(5).astype(np.int64)
        res_y = np.array([13]).astype(np.float32)
        cond = np.array(1).astype(bool)
        res_scan = np.array([-1, 1, 4, 8, 13]).astype(np.float32).reshape((5, 1))
        # expect(node, inputs=[trip_count, cond, y], outputs=[res_y, res_scan],
        #        name='test_loop11', opset_imports=[onnx.helper.make_opsetid("", 11)])

        interp = Interpreter()
        cfg_precise = AbstractionInitConfig(diff=True, from_init=True, stride=1)
        abst_trip_count = Abstraction().load(cfg_precise, 'trip_count', trip_count.shape, 'INT', trip_count)
        abst_cond = Abstraction().load(cfg_precise, 'cond', cond.shape, 'BOOL', cond)
        abst_y = Abstraction().load(cfg_precise, 'y', y.shape, 'INT', y)

        outputs, _ = interp.interp_Loop([abst_trip_count, abst_cond, abst_y], node, 'Loop', 'res_y')

        self.assertTrue(correct_abstraction(outputs[0], np.array([13]), tight=True))
        self.assertTrue(correct_abstraction(outputs[1], np.array([-1,1,4,8,13]).reshape((5,1)), tight=True))

    def test_loop_13(self):
        # case loop_13 from https://github.com/onnx/onnx/blob/master/docs/Operators.md#Loop
        # Given a tensor x of values [x1, ..., xN],
        # Return a sequence of tensors of
        #   [[x1], [x1, x2], ..., [x1, ..., xN]]

        seq_in = onnx.helper.make_sequence_value_info('seq_in', onnx.TensorProto.FLOAT, None)
        seq_out = onnx.helper.make_sequence_value_info('seq_out', onnx.TensorProto.FLOAT, None)
        cond_in = onnx.helper.make_tensor_value_info('cond_in', onnx.TensorProto.BOOL, [])
        cond_out = onnx.helper.make_tensor_value_info('cond_out', onnx.TensorProto.BOOL, [])
        iter_count = onnx.helper.make_tensor_value_info('iter_count', onnx.TensorProto.INT64, [])

        x = np.array([1, 2, 3, 4, 5]).astype(np.float32)

        x_const_node = onnx.helper.make_node(
            'Constant',
            inputs=[],
            outputs=['x'],
            value=onnx.helper.make_tensor(
                name='const_tensor_x',
                data_type=onnx.TensorProto.FLOAT,
                dims=x.shape,
                vals=x.flatten().astype(float),
            )
        )

        one_const_node = onnx.helper.make_node(
            'Constant',
            inputs=[],
            outputs=['one'],
            value=onnx.helper.make_tensor(
                name='const_tensor_one',
                data_type=onnx.TensorProto.INT64,
                dims=(),
                vals=[1]
            )
        )

        zero_const_node = onnx.helper.make_node(
            'Constant',
            inputs=[],
            outputs=['slice_start'],
            value=onnx.helper.make_tensor(
                name='const_tensor_zero',
                data_type=onnx.TensorProto.INT64,
                dims=(1,),
                vals=[0]
            )
        )

        axes_node = onnx.helper.make_node(
            'Constant',
            inputs=[],
            outputs=['axes'],
            value=onnx.helper.make_tensor(
                name='const_tensor_axes',
                data_type=onnx.TensorProto.INT64,
                dims=(1,),
                vals=[0]
            )
        )

        add_node = onnx.helper.make_node(
            'Add',
            inputs=['iter_count', 'one'],
            outputs=['end']
        )

        # end_unsqueeze_node = onnx.helper.make_node(
        #     'Unsqueeze',
        #     inputs=['end', 'axes'],
        #     outputs=['slice_end']
        # )

        slice_node = onnx.helper.make_node(
            'Slice',
            inputs=['x', 'slice_start', 'end'],
            outputs=['slice_out']
        )

        insert_node = onnx.helper.make_node(
            'SequenceInsert',
            inputs=['seq_in', 'slice_out'],
            outputs=['seq_out']
        )

        identity_node = onnx.helper.make_node(
            'Identity',
            inputs=['cond_in'],
            outputs=['cond_out']
        )

        loop_body = onnx.helper.make_graph(
            [identity_node, x_const_node, one_const_node, zero_const_node, add_node,
             axes_node, slice_node, insert_node],
            'loop_body',
            [iter_count, cond_in, seq_in],
            [cond_out, seq_out]
        )

        node = onnx.helper.make_node(
            'Loop',
            inputs=['trip_count', 'cond', 'seq_empty'],
            outputs=['seq_res'],
            body=loop_body
        )

        trip_count = np.array(5).astype(np.int64)
        seq_empty = []  # type: List[Any]
        seq_res = [x[:int(i)] for i in x]
        cond = np.array(1).astype(bool)

        interp = Interpreter()
        cfg_precise = AbstractionInitConfig(diff=True, from_init=True, stride=1)
        abst_trip_count = Abstraction().load(cfg_precise, 'trip_count', trip_count.shape, 'INT', trip_count)
        abst_seq_empty = Abstraction().load(cfg_precise, 'seq_empty', [1], 'INT', seq_empty)
        abst_cond = Abstraction().load(cfg_precise, 'cond', cond.shape, 'BOOL', cond)

        outputs, _ = interp.interp_Loop([abst_trip_count, abst_cond, abst_seq_empty], node, 'Loop', 'output')

        seq_res = [x[:int(i)] for i in x]
        # outputs[0].print()

        self.assertTrue(correct_abstraction(outputs[0], seq_res))

if __name__ == '__main__':
    unittest.main()


'''
Дано число K и список А размера N. Найти элемент списка, который наиболее
близок к числу К (то есть такой элемент Акб для которого величина |Ак - К|
является минимальной).
'''

def solution(K, A: list, N: int):
    diff = float("infinity")
    best = 0
    for i in A:
        cur = abs(i - K)
        if cur < diff:
            diff = cur
            best = i

    return best

A = [4, 5.6, 6.5, 4.25, 10, 15.4]
K = 7
print(f"Список: {A} k = {K}")
print(f"Результат: {solution(K, A, len(A))}")


from django.core.mail import EmailMessage
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string

from .tokens import user_activation_token

def send_email(user, request, mail_subject, template_name, to_email):
    current_site = get_current_site(request)
    mail_subject = mail_subject
    if current_site.domain == 'localhost':
        port = ':1337'
        protocol ='http'
    else:
        port = ''
        protocol = 'https'
    message = render_to_string(template_name, {
        'user': '%s %s' %(user.first_name, user.last_name),
        'domain': current_site.domain,
        'port': '%s' % port,
        'protocol': protocol,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'token': user_activation_token.make_token(user),
        'new_email': to_email
    })
    email = EmailMessage(mail_subject, message, to=[to_email])
    email.send()


#from selenium import webdriver
#from selenium.webdriver.common.by import By
#import time
#from selenium.webdriver import ActionChains
from pages.home.login_pages import LoginPage
from utilities.teststatus import TestStatus
import unittest
import pytest

@pytest.mark.usefixtures("oneTimeSetUp","setUp")
class LoginTests(unittest.TestCase):
    @pytest.fixture(autouse=True)
    def classSetup(self, oneTimeSetUp):
        self.lp = LoginPage(self.driver)
        self.ts = TestStatus(self.driver)

    @pytest.mark.run(order=1)
    def test_validLogin(self):
        #self.driver.get(self.baseURL)
        #self.lp = LoginPage(self.driver)
        self.lp.login("preeti_pradhan2005@yahoo.co.in", "Mylord_03")
        result1 = self.lp.verifyLoginTitle()
        #assert result1 == True
        self.ts.mark(result1,"TitleVerification")

        result2 = self.lp.verifyLoginSuccessful()
        self.ts.markFinal("test_validLogin",result2,"LoginVerification")

        #assert result2 == True

'''
    @pytest.mark.run(order=2)
    def test_InvalidLogin(self):

    # baseURL = "https://www.amazon.in/"
    # self.driver.get(self.baseURL)
    # self.lp = LoginPage(self.driver)

        self.lp.login("preeti_pradhan2005@yahoo.co.in", "mylord_03")

        result = self.lp.verifyLoginFaild()

        assert result == True
'''


from enum import Enum

from selenium_util.locator import Locator
from selenium.webdriver.common.by import By

from pages.mortgage_rates_page import MortgageRatesPage
from pages.zillow_base_page import ZillowBasePage
from utilities.mortgage_math import calculate_payment

class LoanPrograms(Enum):
    """
    A class to represent the loan programs that are available in the web select element

    Note to developer, if you change the structure of this enum, make sure you fix all references to it, there are some
    references to the 0th and 1st indexes of the tuple values
    """
    FIXED_30 = ("Fixed30Year", 30)
    FIXED_15 = ("Fixed15Year", 15)
    ARM_5 = ("ARM5", 5)

    @staticmethod
    def lookup(html_value):
        """
        If you have an html value and you need the corresponding enum, use this static helper method
        :param html_value: the html "value" attribute on a <option> that you would like the enum for
        :return: The enum that represents that value
        """
        for program in LoanPrograms:
            if program.value[0] == html_value:
                return program
        assert False, "Failed to find [" + html_value + "] in LoanPrograms enum, please add a new enum value"

class MortgageCalcPage(ZillowBasePage):
    """
    Class that represents the mortgage calculator web page, inherits from ZillowBasePage

    ...

    Attributes
    ----------
    driver : webdriver
        webdriver that this page will use to interact with the web page, defined in parent class
    various locators : Locator
        Locator objects that define ways to find web elements on this page, see decelerations below

    Methods
    -------
    See below - numerous methods for setting, and asserting different web elements on this page
    """

    '''
    ***** BEGIN LOCATORS *****
    '''

    _HOME_PRICE_INPUT = Locator(By.ID, "homePrice")

    _DOWN_PAYMENT_PERCENT_INPUT = Locator(By.ID, "form-1_downPaymentPercent")
    _DOWN_PAYMENT_AMOUNT_INPUT = Locator(By.ID, "form-1_downPayment")

    _TERM_SELECT = Locator(By.ID, "form-1_term")

    _RATE_INPUT = Locator(By.ID, 'rate')
    _RATE_HELP_BUTTON = Locator(By.XPATH, "//span[text()=\"More info on Interest rate\"]/ancestor::button")
    # TODO ask dev for an ID on this element, this is the best way to locate the element currently and it is decently
    #  fragile to future changes
    _SEE_CURRENT_RATES_LINK = Locator(By.XPATH, "//a[text()=\"See current rates\"]")
    _RATE_ERROR_MESSAGE = Locator(By.CSS_SELECTOR, "[class*=StyledFormHelp]")

    # TODO ask dev for an ID on this element, this is the best way to locate the element currently and it is very
    #  fragile to future changes
    _ADVANCED_BUTTON = Locator(By.XPATH, "//button[text() = \"Advanced\"]")

    _PMI_CHECKBOX = Locator(By.ID, "form-1_includePMI")
    _TAXES_INSURANCE_CHECKBOX = Locator(By.ID, "form-1_includeTaxesInsurance")

    _TAXES_INPUT = Locator(By.ID, "form-1_propertyTaxRateAnnualAmount")
    _INSURANCE_INPUT = Locator(By.ID, "annualHomeownersInsurance")

    # TODO ask dev for an ID on this element, this is the best way to locate the element currently and it is very
    #  fragile to future changes
    _PAYMENT_TEXT = Locator(By.CSS_SELECTOR, "[y=\"20\"]")

    '''
    ***** END LOCATORS *****
    '''

    def __init__(self, driver):
        """
        Create a new MortgageCalcPage
        Assumes you have already navigated to this page, and will wait for the mortgage rate input element to be
        clickable before returning your new page object to you
        :param driver: webdriver that this page will use to interact with the web page
        """
        super().__init__(driver)
        self.wait_for_element_to_exist(self._RATE_INPUT).wait_for_element_to_be_clickable()

    def set_interest_rate(self, rate):
        """
        Set the interest rate to the given value
        :param rate: rate to set, can be any type, eventually it will be casted to string for entry
        :return: self, this page object after any changes
        """
        # TODO if pressing enter bug on Interest rate input is fixed, we could make this method send the enter key
        #  and then we could remove the click of payment
        self.get_element(self._RATE_INPUT).set_text(rate)
        # click on something else to make the input field lose focus and cause a re-calculation
        self.get_element(self._PAYMENT_TEXT).click()
        return self

    def assert_interest_rate(self, expected_rate):
        """
        assert that the interest rate input has an expected value
        :param expected_rate: the rate you expect
        :return: self, this page object after any changes
        """
        actual_value = self.get_element(self._RATE_INPUT).get_value()

        assert actual_value == expected_rate, \
            "Expected interest rate to be [" + expected_rate + "] but it was [" + actual_value + "]"
        return self

    def assert_interest_rate_has_value(self):
        """
        Simple assertion, just verifies that the interest rate input has a value
        :return: self, this page object after any changes
        """
        actual_value = self.get_element(self._RATE_INPUT).get_value()

        assert float(actual_value) > 0, \
            "Expected interest rate to be a non empty value greater than 0 but it was [" + actual_value + "]"
        return self

    def assert_payment(self, expected_payment):
        """
        Assert the calculated payment on the web page is the expected value
        :param expected_payment: numeric value of what you expect the payment to be
        :return: self, this page object after any changes
        """

        # add a $ and strip off an decimal places in the expected
        expected_payment = "${:,.0f}".format(expected_payment)

        payment_element = self.get_element(self._PAYMENT_TEXT)
        # We might have just changed an input,
        # give the payment element a chance to update if it hasn't yet (race condition)
        payment_element.wait_for_element_to_have_text(expected_payment)
        actual_value = payment_element.get_text()

        print("Asserting payment is [" + expected_payment + "]")

        # note we are comparing strings here
        assert actual_value == expected_payment, \
            "Expected payment to be [" + expected_payment + "] but it was [" + actual_value + "]"
        return self

    def assert_payment_given_input_values(self):
        """
        Assertion method to assert that based on what value all of the inputs have, the displayed calculation is correct
        This method was created to specifically test that when the page loads, it loads with all of the inputs having
        a value, and that the displayed calculation is correct based on those values.

        This method should NOT be used in place of assert_payment to prevent false positives. It's better practice to
        fully calculate the payment yourself, based on what you inputted

        :return: self, this page object after any changes
        """
        price = float(self.get_element(self._HOME_PRICE_INPUT).get_value().replace(",", ""))
        down_payment = float(self.get_element(self._DOWN_PAYMENT_AMOUNT_INPUT).get_value().replace(",", ""))

        term_selected = self.get_select_element(self._TERM_SELECT).get_selected_value()
        loan_program = LoanPrograms.lookup(term_selected)

        rate = float(self.get_element(self._RATE_INPUT).get_value())

        calculated_payment = calculate_payment(price, down_payment, rate, loan_program)

        monthly_taxes = float(self.get_element(self._TAXES_INPUT).get_value().replace(",", "")) / 12
        monthly_insurance = float(self.get_element(self._INSURANCE_INPUT).get_value().replace(",", "")) / 12

        # our calculation above does not consider taxes and insurance, so now that we have scraped them off the page,
        # add them into to our expected total
        total_payment = calculated_payment + monthly_taxes + monthly_insurance

        self.assert_payment(total_payment)

        return self

    def set_home_price(self, home_price):
        """
        Set the home price input to the desired value
        :param home_price: value to enter into the input, will be casted to string
        :return: self, this page object after any changes
        """
        self.get_element(self._HOME_PRICE_INPUT).set_text(home_price)
        return self

    def set_down_payment_percent(self, percent):
        """
        Set the down payment percent input to the desired value (numeric or string accepted)
        Note your percent should not include a % if you choose to pass a string
        :param percent: desired percent (numeric or string accepted)
        :return: self, this page object after any changes
        """
        self.get_element(self._DOWN_PAYMENT_PERCENT_INPUT).set_text(percent, True)
        return self

    def assert_down_payment_percent(self, expected_percent):
        """
        Assert the down payment percent input is the expected value
        :param expected_percent: value to assert against the input, should be numeric
        :return: self, this page object after any changes
        """
        percent_element = self.get_element(self._DOWN_PAYMENT_PERCENT_INPUT)
        percent_element.wait_for_element_to_have_value(expected_percent, True)
        actual_value = percent_element.get_value()
        assert float(actual_value) == float(expected_percent), \
            "Expected down payment percent to be [" + str(expected_percent) + "] but it was [" + str(actual_value) + "]"
        return self

    def set_down_payment_amount(self, amount):
        """
        Set the down payment amount input to the desired value
        :param amount: desired value, will be casted to string before entered
        :return: self, this page object after any changes
        """
        self.get_element(self._DOWN_PAYMENT_AMOUNT_INPUT).set_text(amount, True)
        return self

    def assert_down_payment_amount(self, expected_amount):
        """
        Assert that the down payment amount has an expected value
        :param expected_amount: numeric value that you expect the input to have
        :return: self, this page object after any changes
        """

        # Add in commas to your expected amount and remove any decimal places
        expected_amount = "{:,.0f}".format(expected_amount)

        actual_value = self.get_element(self._DOWN_PAYMENT_AMOUNT_INPUT).get_value()

        # note comparing strings here
        assert actual_value == expected_amount, \
            "Expected down payment to be [" + str(expected_amount) + "] but it was [" + str(actual_value) + "]"
        return self

    def select_loan_program(self, loan_program: LoanPrograms):
        """
        Select the desired loan program in the drop-down
        :param loan_program: Enum for the value you would like selected
        :return: self, this page object after any changes
        """
        # 0th index of the loan program value is the html value attribute for that choice
        self.get_select_element(self._TERM_SELECT).select_by_value(loan_program.value[0])
        return self

    def _open_advanced(self):
        """
        Open the advanced drop down to expose the advanced options, smart enough to first determine if it is already
        open and do nothing
        """
        optional_element = self.get_element_if_exists(self._ADVANCED_BUTTON)

        if optional_element is not None:
            optional_element.click()
            self.wait_for_element_to_exist(self._TAXES_INSURANCE_CHECKBOX)

        # private method that does not refresh the page, does not need to return self

    def check_taxes_insurance(self, check):
        """
        Check or uncheck the taxes/insurance checkbox based on your desired value
        :param check: true to check the box, false to uncheck it
        :return: self, this page object after any changes
        """
        self._open_advanced()
        self.get_checkbox_element(self._TAXES_INSURANCE_CHECKBOX).check(check)
        return self

    def check_pmi(self, check):
        """
        Check or uncheck the PMI checkbox based on your desired value
        :param check: true to check the box, false to uncheck it
        :return: self, this page object after any changes
        """
        self._open_advanced()
        self.get_checkbox_element(self._PMI_CHECKBOX).check(check)
        return self

    def assert_interest_help_modal_opens_and_closes(self, click_x):
        """
        Assert that the interest help modal will open, be click-able and then assert that it closes if someone clicks
        off the modal, or clicks the close x button
        :param click_x: do you want to click the x button (True) or do you want to click off the modal (FALSE)
        :return: self, this page object after any changes
        """

        # create locator inline because it is very unlikely that any other method in this class will ever need it. If
        # that changes, move this to a class deceleration
        modal_p_loc = Locator(By.XPATH, "//p[contains(text(), \"Representative interest rates\")]")

        # Assert that the modal is not open, needed to prove we can tell it's not open
        assert len(self.driver.find_elements(*modal_p_loc.as_args())) == 0, \
            "Found modal in DOM before trying to open it, this means our next assertion cannot prove " \
            "that the modal is actually open"

        self.get_element(self._RATE_HELP_BUTTON).click()

        # Wait for the modal to open and be click-able, if either of these fail this test will fail before the assertion
        modal_p_element = self.wait_for_element_to_exist(modal_p_loc)
        modal_p_element.wait_for_element_to_be_clickable()

        # Technically covered by the conditions above, but a good sanity check
        assert len(self.driver.find_elements(*modal_p_loc.as_args())) == 1, \
            "Interest rate help modal did not open"

        if click_x:
            # create locator inline because it is very unlikely that any other method in this class will ever need it.
            # If that changes, move this to a class deceleration
            self.get_element(Locator(By.CSS_SELECTOR, "[class*=CloseButton]")).click()
        else:
            # click somewhere else to close the modal
            self.get_element(self._PAYMENT_TEXT).click()

        # Wait until the modal is no longer in the DOM
        modal_p_element.wait_for_element_to_be_stale()

        # Technically covered by the condition above, but a good sanity check to make sure it's actually gone
        assert len(self.driver.find_elements(*modal_p_loc.as_args())) == 0, \
            "Found modal after it was supposedly closed"

        return self

    def click_see_current_rates(self):
        """
        Click the see current rates link and navigate to that page
        :return: a new MortgageRatesPage as a result of navigation
        """
        # Note! opens in a new tab
        self.get_element(self._SEE_CURRENT_RATES_LINK).click()
        # close the current window
        self.driver.close()
        # switch to the new tab we opened
        self.driver.switch_to.window(self.driver.window_handles[0])
        return MortgageRatesPage(self.driver)

    def assert_interest_rate_error_message(self, expected_message):
        """
        Assert the interest rate error message
        :param expected_message: error message that you expect to be showing
        :return: self, this page object after any changes
        """
        message_p_element = self.wait_for_element_to_exist(self._RATE_ERROR_MESSAGE)
        actual_message = message_p_element.get_text()

        assert actual_message == expected_message, \
            "Expected down payment percent to be [" + expected_message + "] but it was [" + actual_message + "]"
        return self

    def assert_no_interest_rate_error_message(self):
        """
        Assert that the interest rate input does NOT have any error messages
        :return: self, this page object after any changes
        """
        potential_message_elements = self.get_elements(self._RATE_ERROR_MESSAGE)

        assert len(potential_message_elements) == 0, \
            "Unexpected error message found: " + potential_message_elements[0].get_text()
        return self


from django.shortcuts import get_object_or_404

from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated

from project.models import Project

from ...models import ProjectTeamRole
from ..serializers.role import TeamRoleSerializer

class TeamRoleViewSet(
        viewsets.ModelViewSet):

    model = ProjectTeamRole
    permission_classes = (IsAuthenticated,)
    serializer_class = TeamRoleSerializer
    pagination_class = None

    @property
    def project(self):
        return get_object_or_404(Project, pk=self.kwargs.get('project_pk'))

    def get_queryset(self):
        user = self.request.user

        if user.is_superuser:
            queryset = self.model.objects.filter(
                project_id=self.kwargs.get('project_pk'))
        else:
            queryset = self.model.objects.filter(
                project_id=self.kwargs.get('project_pk'),
                project__created_by=user)

        return queryset


import numpy as np
import matplotlib.pyplot as plt

def MC_Ising_model(beta, vis = False, N = 50, rng = 3000):
  s = np.random.choice([-1, 1],[N,N])
  numbers = np.arange(N*N).reshape(N,N)
  M_list = []
  blacks = ((numbers//N + numbers%N)%2).astype(bool)
  whites = np.logical_not(blacks)

  if vis == True:
    plt.rcParams['image.cmap'] = 'Wistia'
    fig, ax = plt.subplots(figsize=(16, 9))
    ax.imshow(s, vmin=0, vmax=1)
    ax.axis(False);

  for j in range(rng):
    m_i = np.roll(s, 1, axis=0)
    m_i += np.roll(s, -1, axis=0)
    m_i += np.roll(s, 1, axis=1)
    m_i += np.roll(s, -1, axis=1)

    p = 1/(1+np.exp(-2*beta*m_i))
    p = p.reshape(N,N)

    rand = np.random.random([N,N])
    up = np.where(p >= rand, True, False).reshape(N,N)

    steps = np.random.choice([0, 1],2)

    for i in steps:
      if i == 0:
        s[whites] = -1
        s[whites & up] = +1
      else:
        s[blacks] = -1
        s[blacks & up] = +1

    if j > rng/2:
      M = np.abs(np.mean(s))
      M_list.append(M)

  if vis == True:
    plt.rcParams['image.cmap'] = 'Wistia'
    fig, ax = plt.subplots(figsize=(16, 9))
    ax.imshow(s, vmin=0, vmax=1)
    ax.axis(False);

  M_mean = np.mean(M_list)
  chi = np.var(M_list)*beta

  M_list.clear()

  return M_mean, chi

betas = np.linspace(0.2,2,num=40)
print(betas)
data = []

for beta in betas:
  mb = []
  cb = []
  for i in range(10):
    values = (MC_Ising_model(beta))
    mb.append(values[0])
    cb.append(values[1])
  print(beta, np.mean(mb), np.mean(cb))
  data.append([beta, np.mean(mb), np.mean(cb)])

data = np.array(data)
b = data[:,0]
m = data[:,1]
c = data[:,2]

plt.plot(b, m)
plt.show()
plt.plot(b, c)
plt.show()


#!/usr/bin/python3
"""This is the 0-add_integer module."""

def add_integer(a, b=98):
    """Does the addition of two integers"""
    """Arguments a and b can be integer or float"""
    """Return:a + b or raise error if input not a number"""
    if isinstance(a, str) or a is None:
        raise TypeError("a must be an integer")
    if isinstance(b, str) or b is None:
        raise TypeError("b must be an integer")
    a = int(a)
    b = int(b)
    return (a + b)


# -*- coding: utf-8 -*-
import jft

fin = open("chichi.csv", "r")
fout = open("food.json", "w")

fout.write('[')
preb = ""
prer = ""
for line in fin.readlines():
    while line[-1] == '\n' or line[-1] == '\r':
        line = line[0:-1]
    line = line.replace('\\', '\\\\')
    arr = line.split('\t')
    photographer = arr[0]
    name = arr[1]
    taste = arr[2]
    restaurant = arr[3]
    if (restaurant == '哈乐餐厅'):
        building = "哈乐"
    else:
        building = restaurant[0:6]
        restaurant = restaurant[6:]
    price = arr[4]
    description = arr[5]
    url = arr[6]
    genre = ""

    if (preb == ''):
        fout.write('{'
                   + '"building":"' + building + '",'
                   + '"restaurants":[{'
                     '"restaurant":"' + restaurant + '",'
                   + '"foods":['
        )
    else:
        if (prer != restaurant):
            fout.write(']}')
            if (preb != building):
                fout.write(']},'
                           + '{'
                           + '"building":"' + building + '",'
                           + '"restaurants":['
                )
            else:
                fout.write(',')
            fout.write('{' +
                       '"restaurant":"' + restaurant + '",'
                       + '"foods":['
            )
        else:
            fout.write(',')

    fout.write('{'
               + '"name":"' + jft.j2f("utf8", "utf8", name) + '",'
               + '"url":"' + url + '",'
               + '"genre":"' + genre + '",'
               + '"price":"¥' + price + '",'
               + '"taste":"' + taste + '",'
               + '"description":"' + description + '",'
               + '"photographer":"' + photographer + '"'
               + '}'
    )
    preb = building
    prer = restaurant
fout.write(']}]}]')


# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final mostre:
    # A média de idade do grupo.
    # Qual o nome do homem mais velho.
    # Quantas mulheres tem menos de 20 anos.

from datetime import date

# Variáveis de controle:
idadeh = 0
nm_h = ''
nm_m = ''
sx = ''
idadem = 0
somaidade = 0

# Objetos principais:
ano_at = date.today().year

# Algoritmo:

for i in range(1, 5, 1):
    print('----- {}ª PESSOA -----'.format(i))
    nome = str(input('Diga o nome da {}ª pessoa:\n'.format(i))).upper().strip()
    sexo = str(input('Qual o sexo da {}ª pessoa (m/h):\n'.format(i))).upper().strip()
    idadei = int(input('Por fim, em que ano nasceu a pessoa?\n'))
    somaidade += (ano_at - idadei)
    if i == 1:
        if sexo == 'H':
            nm_h = nome
            idadeh = ano_at - idadei
        else:
            nm_m = nome
            idadem += 1
    else:
        if sexo == 'H' and (ano_at - idadei) > idadeh:
            nm_h = nome
            idadeh = ano_at - idadei
        if sexo == 'M':
            if (ano_at - idadei) < 20:
                idadem += 1

média_idade = somaidade/i

print('O homem mais velho é {}, com {} anos.'.format(nm_h,idadeh))
print('A média_idade do grupo é {} anos.'.format(média_idade))
print('Existem {} mulheres com menos de 20 anos.'.format(idadem))


from datetime import datetime       # needed to read and compare dates

class item:     # initiates item class for all inventory elements

    def __init__(self, itemID=0, manuF='none', itemT='none', itemP=0.0, serv=datetime.today(), dmg='False'):
        self.itemID = itemID
        self.manuF = manuF
        self.itemT = itemT
        self.itemP = itemP
        self.serv = serv
        self.dmg = dmg

if __name__ == "__main__":
    full_table = {}     # Dictionary to hold all inventory elements for retrieval
    item_type = []
    itemID_List = []
    dmg_inv = []        # Lists for sorting
    manuF_list = []
    date_list = []
    price_list = []

    import csv      # Needed for csv manipulation

    with open('ManufacturerList.csv', 'r') as csvfile:      # Opens/reads manufacturer list
        list_reader = csv.reader(csvfile)
        for row in list_reader:     # Takes rows from csv and adds them to line
            line = item()           # Classifies line as an item
            line.itemID = row[0]
            line.manuF = row[1]     # Places elements in required organizational structure in line
            line.itemT = row[2]
            line.dmg = row[3]
            full_table[line.itemID] = line  # Defines ItemID as key and adds line items to Full Table dictionary

    with open('PriceList.csv', 'r') as csvfile:     # Opens/reads price list and add missing elements to Full table dictionary
        list_reader = csv.reader(csvfile)
        for row in list_reader:                     # Adds any missing elements
            full_table[row[0]].itemP = row[1]

    with open('ServiceDatesList.csv','r') as csvfile:       # Opens/reads service list and adds missing elements
        list_reader = csv.reader(csvfile)
        date_format = '%m/%d/%Y'    # Format for datetime
        for row in list_reader:
            new_date = datetime.strptime(row[1], date_format).date()    # strips dates
            full_table[row[0]].serv = new_date                          # adds elements to table

    for i in full_table:    # creates a list of just manufacturers
        manuF_list.append(full_table[i].manuF)
    manuF_list.sort()       # sorts manufacturer list
    manuF = {}              # placed in dictionary

    for i in manuF_list:    # specified key to ensure unique values
        manuF[i] = i
    with open('FullInventory.csv', 'w', newline='') as csvfile:     # opens for writing
        line_writer = csv.writer(csvfile)
        for i in manuF:                                            # iterates and adds sorted elements to csv
            for j in full_table:
                if full_table[j].manuF == i:
                    line_writer.writerow([full_table[j].itemID, full_table[j].manuF,
                                            full_table[j].itemT, full_table[j].itemP,
                                            full_table[j].serv, full_table[j].dmg])

    for i in full_table:                        # creates list for item type
        item_type.append(full_table[i].itemT)
    item_type.sort()                            # sorts item types
    itemT = {}
    for i in item_type:                         # ensures unique values
        itemT[i] = i
    for i in full_table:                        # creates list for ItemID
        itemID_List.append(full_table[i].itemID)
    itemID_List.sort()                          # sorts item ID
    for i in itemT:
        with open(f'{i.capitalize()}Inventory.csv', 'w', newline='') as csvfile:  # opens capitalized variable named csv for writing
            line_writer = csv.writer(csvfile)
            for j in itemID_List:
                for k in full_table:
                    if full_table[k].itemID == j:   # iterates and writes needed elements to file
                        line_writer.writerow([full_table[k].itemID, full_table[k].manuF,
                                              full_table[k].itemP, full_table[k].serv,
                                              full_table[k].dmg])

    for i in full_table:                       # creation of date list table
        date_list.append(full_table[i].serv)
    date_list.sort()
    dates = {}
    for i in date_list:                        # ensure unique values
        dates[i] = i

    with open('PastServiceDateInventory.csv', 'w', newline='') as csvfile:  # opens past service csv for writing
        line_writer = csv.writer(csvfile)
        for i in dates:
            for j in full_table:
                if datetime.today().date() > full_table[j].serv and full_table[j].serv == i:    #compared today's date with the service due date
                    line_writer.writerow([full_table[j].itemID, full_table[j].manuF,
                                          full_table[j].itemT, full_table[j].itemP,
                                          full_table[j].serv, full_table[j].dmg],)

    for i in full_table:        # adds prices to list
        price_list.append(full_table[i].itemP)

    price_list.sort()           # sorts prices
    prices = {}
    for i in price_list:        # ensures unique price values
        prices[i] = i

    with open('DamagedInventory.csv','w', newline='') as csvfile:   # opens csv to write damaged inventory
        line_writer = csv.writer(csvfile)
        for i in prices:
            for j in full_table:
                if full_table[j].dmg == 'damaged' and full_table[j].itemP == i:     # checks if item flagged as damaged
                    line_writer.writerow([full_table[j].itemID, full_table[j].manuF,    # writes rows with relevant information
                                          full_table[j].itemT, full_table[j].itemP,
                                          full_table[j].serv])
    print('Reports generated.')

FinalProject - Part 1/FinalProjectPart1.py


"""Define the Autorization Manager."""
from datetime import datetime, timedelta
from typing import Optional

import jwt
from fastapi import BackgroundTasks, Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from app.config.settings import get_settings
from app.database.db import get_database
from app.managers.email import EmailManager
from app.models.enums import RoleType
from app.models.user import User
from app.schemas.email import EmailTemplateSchema
from app.schemas.request.auth import TokenRefreshRequest

class ResponseMessages:
    """Error strings for different circumstances."""

    CANT_GENERATE_JWT = "Unable to generate the JWT"
    CANT_GENERATE_REFRESH = "Unable to generate the Refresh Token"
    CANT_GENERATE_VERIFY = "Unable to generate the Verification Token"
    INVALID_TOKEN = "That token is Invalid"  # nosec
    EXPIRED_TOKEN = "That token has Expired"  # nosec
    VERIFICATION_SUCCESS = "User succesfully Verified"
    USER_NOT_FOUND = "User not Found"
    ALREADY_VALIDATED = "You are already validated"
    VALIDATION_RESENT = "Validation email re-sent"

class AuthManager:
    """Handle the JWT Auth."""

    @staticmethod
    def encode_token(user):
        """Create and return a JTW token."""
        try:
            payload = {
                "sub": user["id"],
                "exp": datetime.utcnow()
                + timedelta(minutes=get_settings().access_token_expire_minutes),
            }
            return jwt.encode(
                payload, get_settings().secret_key, algorithm="HS256"
            )
        except Exception as exc:
            # log the exception
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.CANT_GENERATE_JWT
            ) from exc

    @staticmethod
    def encode_refresh_token(user):
        """Create and return a JTW token."""
        try:
            payload = {
                "sub": user["id"],
                "exp": datetime.utcnow() + timedelta(minutes=60 * 24 * 30),
                "typ": "refresh",
            }
            return jwt.encode(
                payload, get_settings().secret_key, algorithm="HS256"
            )
        except Exception as exc:
            # log the exception
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED,
                ResponseMessages.CANT_GENERATE_REFRESH,
            ) from exc

    @staticmethod
    def encode_verify_token(user):
        """Create and return a JTW token."""
        try:
            payload = {
                "sub": user["id"],
                "exp": datetime.utcnow() + timedelta(minutes=10),
                "typ": "verify",
            }
            return jwt.encode(
                payload, get_settings().secret_key, algorithm="HS256"
            )
        except Exception as exc:
            # log the exception
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED,
                ResponseMessages.CANT_GENERATE_VERIFY,
            ) from exc

    @staticmethod
    async def refresh(refresh_token: TokenRefreshRequest, database):
        """Refresh an expired JWT token, given a valid Refresh token."""
        try:
            payload = jwt.decode(
                refresh_token.refresh,
                get_settings().secret_key,
                algorithms=["HS256"],
            )

            if payload["typ"] != "refresh":
                raise HTTPException(
                    status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
                )

            user_data = await database.fetch_one(
                User.select().where(User.c.id == payload["sub"])
            )

            if not user_data:
                raise HTTPException(
                    status.HTTP_404_NOT_FOUND, ResponseMessages.USER_NOT_FOUND
                )

            # block a banned user
            if user_data["banned"]:
                raise HTTPException(
                    status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
                )
            new_token = AuthManager.encode_token(user_data)
            return new_token

        except jwt.ExpiredSignatureError as exc:
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.EXPIRED_TOKEN
            ) from exc
        except jwt.InvalidTokenError as exc:
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
            ) from exc

    @staticmethod
    async def verify(code: str, database):
        """Verify a new User's Email using the token they were sent."""
        try:
            payload = jwt.decode(
                code,
                get_settings().secret_key,
                algorithms=["HS256"],
            )
            user_data = await database.fetch_one(
                User.select().where(User.c.id == payload["sub"])
            )

            if not user_data:
                raise HTTPException(
                    status.HTTP_404_NOT_FOUND, ResponseMessages.USER_NOT_FOUND
                )

            if payload["typ"] != "verify":
                raise HTTPException(
                    status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
                )

            # block a banned user
            if user_data["banned"]:
                raise HTTPException(
                    status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
                )

            if user_data["verified"]:
                raise HTTPException(
                    status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
                )

            await database.execute(
                User.update()
                .where(User.c.id == payload["sub"])
                .values(
                    verified=True,
                )
            )
            raise HTTPException(
                status.HTTP_200_OK, ResponseMessages.VERIFICATION_SUCCESS
            )

        except jwt.ExpiredSignatureError as exc:
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.EXPIRED_TOKEN
            ) from exc
        except jwt.InvalidTokenError as exc:
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
            ) from exc

    @staticmethod
    async def resend_verify_code(
        user: int, background_tasks: BackgroundTasks, database
    ):  # pragma: no cover (code not used at this time)
        """Resend the user a verification email."""
        user_data = await database.fetch_one(
            User.select().where(User.c.id == user)
        )

        if not user_data:
            raise HTTPException(
                status.HTTP_404_NOT_FOUND, ResponseMessages.USER_NOT_FOUND
            )

        # block a banned user
        if user_data["banned"]:
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
            )

        if user_data["verified"]:
            raise HTTPException(
                status.HTTP_400_BAD_REQUEST,
                ResponseMessages.ALREADY_VALIDATED,
            )

        email = EmailManager()
        email.template_send(
            background_tasks,
            EmailTemplateSchema(
                recipients=[user_data["email"]],
                subject=f"Welcome to {get_settings().api_title}!",
                body={
                    "application": f"{get_settings().api_title}",
                    "user": user_data["email"],
                    "base_url": get_settings().base_url,
                    "verification": AuthManager.encode_verify_token(user_data),
                },
                template_name="welcome.html",
            ),
        )
        # await email.simple_send(
        #     EmailSchema(
        #         recipients=[user_data["email"]],
        #         subject=f"Welcome to {get_settings().api_title}!",
        #         body="Test Email",
        #     ),
        # )

        raise HTTPException(
            status.HTTP_200_OK, ResponseMessages.VALIDATION_RESENT
        )

class CustomHTTPBearer(HTTPBearer):
    """Our own custom HTTPBearer class."""

    async def __call__(
        self, request: Request, db=Depends(get_database)
    ) -> Optional[HTTPAuthorizationCredentials]:
        """Override the default __call__ function."""
        res = await super().__call__(request)

        try:
            payload = jwt.decode(
                res.credentials, get_settings().secret_key, algorithms=["HS256"]
            )
            user_data = await db.fetch_one(
                User.select().where(User.c.id == payload["sub"])
            )
            # block a banned or unverified user
            if user_data["banned"] or not user_data["verified"]:
                raise HTTPException(
                    status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
                )
            request.state.user = user_data
            return user_data
        except jwt.ExpiredSignatureError as exc:
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.EXPIRED_TOKEN
            ) from exc
        except jwt.InvalidTokenError as exc:
            raise HTTPException(
                status.HTTP_401_UNAUTHORIZED, ResponseMessages.INVALID_TOKEN
            ) from exc

oauth2_schema = CustomHTTPBearer()

def is_admin(request: Request):
    """Block if user is not an Admin."""
    if request.state.user["role"] != RoleType.admin:
        raise HTTPException(status.HTTP_403_FORBIDDEN, "Forbidden")

def can_edit_user(request: Request):
    """Check if the user can edit this resource.

    True if they own the resource or are Admin
    """
    if request.state.user["role"] != RoleType.admin and request.state.user[
        "id"
    ] != int(request.path_params["user_id"]):
        raise HTTPException(status.HTTP_403_FORBIDDEN, "Forbidden")

def is_banned(request: Request):
    """Dont let banned users access the route."""
    if request.state.user["banned"]:
        raise HTTPException(status.HTTP_403_FORBIDDEN, "Banned!")


#!/usr/bin/env python

import json
import numpy as np
from scipy import stats
import os
import sys
from pathlib import Path
import pandas as pd
#from sklearn.cluster import KMeans
from scipy.cluster.vq import vq, kmeans2

# Choosing config file
configFilename = "config-sample.json"
argCount = len(sys.argv)
if(argCount > 1):
    configFilename = sys.argv[1]

# Defining paths
outputDirectory = "output/csv"

if(not os.path.exists(outputDirectory)):
    os.makedirs(outputDirectory)

# Reading config file
with open(configFilename, "r") as fd:
    config = json.load(fd)

print("Loading time series...")

timeseriesFilename = config["tsv"]
nclus = config["nclus"]

print("Loading time series...")
ts = pd.read_csv(timeseriesFilename,sep="\t")

K = np.sum(ts, axis=0)
columns=ts.columns
ts=ts.drop(columns[np.where(K == 0)[0]],axis=1)

# z-scored time series
z = stats.zscore(np.asarray(ts),1)

print("Building edge time series...")
T, N= ts.shape
u,v = np.where(np.triu(np.ones(N),1))           # get edges
# element-wise prroduct of time series
ets = (z[:,u]*z[:,v])
edgeids = {"edgeid"+str(e):edge for e,edge in enumerate(zip(columns[u],columns[v]))}

nclus=int(config['nclus'])
#Clustering edge time series
#etsclus_original=KMeans(n_clusters=nclus, random_state=0).fit(ets).labels_
etsclus=kmeans2(ets,k=nclus)[1]

np.savetxt('output/csv/clustered-edge_timeseries.csv',etsclus,delimiter=',')
with open('output/label.json', 'w') as outfile:
    json.dump(edgeids,outfile)


# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 21:15:55 2020

@author: 龙
"""
import pandas as pd
import numpy as np
from bert_serving.client import BertClient
from termcolor import colored
file_name='D:/bishedata/WikiQACorpus/WikiQA-train.tsv'
out_dir='D:/bishedata/train_question.npy'
train=pd.read_csv(file_name, sep='\t', header=0)
print(train.head())
print(train.shape)

questions=train['Question']#.tolist()
print('Sentence loaded')
print(questions[0:4])
with BertClient(check_length=False) as bc:
    doc_vecs=bc.encode(questions)
    print(type(doc_vecs))
    print('问题转码完成')
    np.save(out_dir,doc_vecs)
    print('存储完成')


import numpy as np
import math
from gym.envs.mujoco import mujoco_env
from gym import utils
from mujoco_py import functions as mjcf
import mujoco_py
#from mujoco_py import mjvisualize as mjcv

def mass_center(model, sim):
    mass = np.expand_dims(model.body_mass, 1)
    xpos = sim.data.xipos
    speed_weights = np.array([0, 10, 5, 3, .2, 5, 3, .2, 15, 25, 5, 3, 5, 3, 0])
    return (np.sum(mass * xpos[:,2] * speed_weights) / np.sum(mass) / np.sum(speed_weights))

def euler_to_quaternion(rot, theta):
        roll = rot*math.cos(theta)
        pitch = rot*math.sin(theta)

        qw = np.cos(roll/2) * np.cos(pitch/2)
        qx = np.cos(roll/2) * np.sin(pitch/2)
        qy = np.sin(roll/2) * np.cos(pitch/2)
        qz = - np.sin(roll/2) * np.sin(pitch/2)

        return [qw, qx, qy, qz]

class Kevin_FallingHumanoidEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(self):
        # timers used to determine end of episode, declared here so they carry over to next timestep
        self.still_timer = 0
        self.begin_timer = 0

        # variable which selects a test scenario if needed
        self.test = 0

        ###### Constants and ranges of initial positions and velocities ######
        # contact force weights
        self.force_weights = np.array([0, 1, 10, 2, 5, .1, .1, 10, 2, 5, .1, .1, 20, 20, 100, 20, 10, 5, 2, 10, 5, 2])

        dtr = math.pi/180 #degrees to radians
        # Initial free and joint positions, qpos[3:7] (rotation) are determined by qrot, so the quaternion can be declared properly
        #                             free trans    free rot       right leg           left leg            abdomen                      right arm                    left arm
        self.init_qpos_low = np.array([0, 0, 0.87,   1, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0,   -35*dtr, -45*dtr, -30*dtr,   -85*dtr, -85*dtr, -90*dtr,   -60*dtr, -60*dtr, -90*dtr])
        self.init_qpos_high= np.array([0, 0, 0.87,   1, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0,   35*dtr , 45*dtr , 75*dtr ,   60*dtr , 60*dtr ,  50*dtr,   85*dtr , 85*dtr , 50*dtr])
        #                             [rotation of fall, direction of fall (0=forward)]
        self.init_qrot_low = np.array([5*dtr, -15*dtr])
        self.init_qrot_high= np.array([15*dtr, 15*dtr])

        # Velocity of fall and initial joint velocities. qvel[0:6] is determined based upon qvel[0 & 3] and qrot[1] (direction of fall), so velocity is always in the direction of the fall
        #                             free trans    free rot     right leg           left leg            abdomen    right arm  left arm
        self.init_qvel_low = np.array([0.3, 0, 0,   0.6, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0,   0, 0, 0,   0, 0, 0])
        self.init_qvel_high= np.array([0.5, 0, 0,   1.0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0,   0, 0, 0,   0, 0, 0])
        ###### End of constants ######

        mujoco_env.MujocoEnv.__init__(self, 'kevin_fallinghumanoid_pelvis_stiff.xml', 2)
        utils.EzPickle.__init__(self)
        print("Kevin Falling Humanoid environment set-up")

    def _get_obs(self):
        data = self.sim.data
        '''
        # Realistic input
        return np.concatenate([data.qpos.flat[np.array([6, 8, 9, 10, 12, 14, 15, 16])],
                               data.qvel.flat[np.array([5, 7, 8, 9, 11, 13, 14, 15])],
                               data.sensordata,
                               -data.site_xmat.flat[np.array([2,5,8, 11,14,17, 20,23,26, 29,32,35, 38,41,44, 47,50,53])],
                               [mjcf.mj_getTotalmass(self.model)],
                               data.qfrc_actuator.flat[np.array([6, 8, 9, 10, 12, 14, 15, 16])]])
        '''
        # Original input
        return np.concatenate([data.qpos.flat[2:],
                               data.qvel.flat,
                               data.cinert.flat[10:-10],
                               data.cvel.flat[6:],
                               data.qfrc_actuator.flat[6:]]) #[np.array([6, 8, 9, 10, 12, 14, 15, 16])]])

    def get_plot_obs(self):
        data = self.sim.data

        impact_force = np.zeros(self.force_weights.shape[0])
        for i in range(data.ncon):
            c_force = np.zeros(6, dtype=np.float64)
            mjcf.mj_contactForce(self.model, data, i, c_force)
            impact_force[data.contact[i].geom1] += c_force[0]
            impact_force[data.contact[i].geom2] += c_force[0]
        impact_force[0]=0.0

        vert_vel = data.cvel[:,2]

        return impact_force, vert_vel

    def step(self, a):
        pos_before = mass_center(self.model, self.sim)
        head_height_before = self.sim.data.body_xpos[14, 2]
        self.do_simulation(a, self.frame_skip)
        pos_after = mass_center(self.model, self.sim)
        data = self.sim.data

        kin_energy_cost = 2 * np.sign(pos_after - pos_before) * np.square(pos_after - pos_before) / self.dt #kinetic energy is measured as the vertical displacement of the total CoM

        head_height_cost = -0.2 * max(min(data.body_xpos[14, 2]-0.3, 0)*((data.body_xpos[14, 2]-head_height_before)/self.dt), 0) # A cost associated to keeping the head as high as possible

        quad_ctrl_cost = 0#-0.002 * np.square(data.ctrl).sum()

        force_normals = np.zeros(self.force_weights.shape[0])
        for i in range(data.ncon):
            c_force = np.zeros(6, dtype=np.float64)
            mjcf.mj_contactForce(self.model, data, i, c_force)
            #if c_force[0] > 5000: c_force[0]*=2
            force_normals[data.contact[i].geom1] += c_force[0]
            force_normals[data.contact[i].geom2] += c_force[0]
            #print("hit bodies are: {:d} and {:d} with force {:f}".format(data.contact[i].geom1, data.contact[i].geom2, c_force[0]), end="\n")
        body_hit_cost = -3e-6 * np.sum(self.force_weights * force_normals) # Cost that is related to the impact force, with different weights for different body parts

        reward = kin_energy_cost + head_height_cost + quad_ctrl_cost + body_hit_cost
        #reward = head_height_cost
        #print("\rkin_energy_cost: {:f} body_hit_cost: {:f} head_height_cost: {:f} quad_ctrl_cost: {:f} reward: {:f}".format(kin_energy_cost, body_hit_cost, head_height_cost, quad_ctrl_cost, reward), end="\n")

        if kin_energy_cost > -0.01:
            self.still_timer+= 1
        else:
            self.still_timer = 0
        self.begin_timer+=1

        done = False#(self.still_timer > 20 and self.begin_timer > 100)
        return self._get_obs(), reward, done, dict(reward_kin_energy=kin_energy_cost, reward_contact_force=body_hit_cost, reward_head_height=head_height_cost)

    def reset_model(self):
        c = 0.01

        qpos, qrot, qvel = self.select_init(c)

        self.still_timer = 0
        self.begin_timer = 0

        self.set_state(qpos, qvel)

        return self._get_obs()

    def viewer_setup(self):
        self.viewer.cam.trackbodyid = 1
        self.viewer.cam.distance = self.model.stat.extent * 1.0
        self.viewer.cam.lookat[2] = 1.0
        self.viewer.cam.elevation = -20

    def select_init(self, c):
        if self.test == 0:
            mjcf.mj_setTotalmass(self.model, self.np_random.uniform(low=70, high=90))
            qpos = self.np_random.uniform(low=self.init_qpos_low, high=self.init_qpos_high) + self.np_random.uniform(low=-c, high=c, size=self.model.nq)
            qrot = self.np_random.uniform(low=self.init_qrot_low, high=self.init_qrot_high)
            qvel = self.np_random.uniform(low=self.init_qvel_low, high=self.init_qvel_high) + self.np_random.uniform(low=-c, high=c, size=self.model.nv)
        else:
            dtr = math.pi/180
            mjcf.mj_setTotalmass(self.model, 80)
            qpos = np.array([0, 0, 0.87,   1, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0,   0, 0, 0,   0, 0, 0])
            qrot = (self.init_qrot_low + self.init_qrot_high)/2
            qvel = (self.init_qvel_low + self.init_qvel_high)/2
            if self.test==2: #minimum mass
                mjcf.mj_setTotalmass(self.model, 70)
            elif self.test==3: # maximum mass
                mjcf.mj_setTotalmass(self.model, 90)
            elif self.test==4: #minimum initial push
                qrot[0] = self.init_qrot_low[0]
                qvel = self.init_qvel_low + 0
            elif self.test==5: #maximum initial push
                qrot[0] = self.init_qrot_high[0]
                qvel = self.init_qvel_high + 0
            elif self.test==6: #most towards the left
                qrot[1] = self.init_qrot_low[1]
            elif self.test==7: #most towards the right
                qrot[1] = self.init_qrot_high[1]
            elif self.test==8: #arms at the sides
                qpos = np.array([0, 0, 0.87,   1, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0,   50*dtr, -30*dtr, -90*dtr,   -50*dtr, 30*dtr, -90*dtr])
            elif self.test==9: #arms aimed backwards
                qpos = np.array([0, 0, 0.87,   1, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0,   0, 0, 0,   -85*dtr, -85*dtr, -90*dtr,   85*dtr, 85*dtr, -90*dtr])

        print("\rNew episode created with, Angle with ground: {:f}  Direction of fall: {:f}  Translational velocity: {:f}  Rotational velocity: {:f}  Mass: {:f}".format(qrot[0], qrot[1], qvel[0], qvel[3], mjcf.mj_getTotalmass(self.model)), end="\n")

        qpos[2] = qpos[2]*math.cos(qrot[0]*0.75)
        qpos[3:7] = euler_to_quaternion(qrot[0], qrot[1])
        self.model.qpos_spring[19:28] = qpos[19:28]
        qvel[0:6] = np.array([qvel[0]*math.cos(qrot[1]), -qvel[0]*math.sin(qrot[1]), 0, qvel[3]*math.sin(qrot[1]), qvel[3]*math.cos(qrot[1]), 0]) + self.np_random.uniform(low=-c, high=c, size=6)

        return qpos, qrot, qvel

    def add_to_test(self, value):
        self.test=(self.test+value)%10

    def get_test(self):
        return self.test
        '''
        #self.viewer.add_overlay()
        fncs = mjcf.__dict__
        #print(dir(mjcf))
        #print(dir(mjcf.mjr_figure))
        figure = mujoco_py.cymj.PyMjvFigure()
        con = mujoco_py.cymj.PyMjrContext()
        rect = mujoco_py.cymj.PyMjrRect()

        mujoco_py.cymj.MjRenderContextWindow()
        figure
        #print(figure.__doc__())
        #print(dir(con))
        #print(dir(rect))
        #print(rect.width)

        mjcf.mjr_figure(rect, figure, con);

        #mjcf.mjv_defaultFigure(figure)
        raise SystemExit(0)
        '''


#function calls inside other function calls. The innermost calls are resolved first. The returned value is used as an argument for the next outer function

#if you enter a decimal number at the prompt below, it will iterate through the functions to eventually convert it to a positive whole number
num = input("Enter a whole positive number:\n")
num = float(num)
num = abs(num)
num = round(num)
print(num)

#the same command can be written in one line of code
print(round(abs(float(input("Enter a whole positive number:\n")))))

Python/Python Tutorial - Bro Code/22 nested function calls.py


#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os, sys, re, time, datetime, logging, random, string, logging.handlers, gzip, paramiko
import multiprocessing, subprocess, requests, urllib3, uuid
from threading import Timer
from configparser import ConfigParser
from Crypto.Cipher import AES

from iscpy.iscpy_dns.named_importer_lib import *
import base64, hashlib, zlib, json, lxml.etree, pexpect, dns, dns.resolver

from time import sleep
import threading, binascii, xml.dom.minidom, shutil

from daemon import Daemon
from waj import *

def get_transfer_ip_and_delay(soa):
	target = 'serial ' + str(soa)
	try:
		with open(run_file) as f:
			l = f.readlines()
			for i in range(len(l)):
				if l[i].find(target) > 0:
					for v in l[i:]:
						if v.find('Transfer completed') > 0:
							res = v
							return int(1000*float(res.split(', ')[-1].split(' ')[0])) , res.split('#')[0].split(' ')[-1]

	except Exception as e:
		logger.warning('get transfer ip and delay error:'+str(e))
	return 0,'0.0.0.0'

def get_server_from_file():
	try:
		server = ''
		with open(standard_source, 'r') as f:
			data = f.read()
			named_data = MakeNamedDict(data)
			servers = named_data['orphan_zones']['.']['options']['masters']
			for ip in servers:
				server += ip + ','
		with open(exigency_source, 'r') as f:
			data = f.read()
			named_data = MakeNamedDict(data)
			servers = named_data['orphan_zones']['.']['options']['masters']
			for ip in servers:
				server += ip + ','
		return server[:-1]

	except Exception as e:
		logger.warning('get server from root source file error:'+str(e))

	return ''

def get_transfer_ip_and_delay_from_file(soa):
	try:
		with open(root_source, 'r') as f:
			data = f.read()
			named_data = MakeNamedDict(data)
			servers = named_data['orphan_zones']['.']['options']['masters']
			dns_query = dns.message.make_query('.', 'SOA')
			for ip in servers:
				begin = datetime.datetime.now()
				res = dns.query.udp(dns_query, ip, port = 53,timeout = 2)
				end = datetime.datetime.now()
				for i in res.answer:
					for j in i.items:
						if j.serial == soa:
							return (end - begin).microseconds//1000,ip
	except Exception as e:
		logger.warning('get transfer ip and delay from swotch_root.zone error:'+str(e))
	return 0,'0.0.0.0'

def get_root_file_size():
	try:
		with open(root_source, 'r') as f:
			data = f.read()
			named_data = MakeNamedDict(data)
			return os.path.getsize(named_data['orphan_zones']['.']['file'])
	except Exception as e:
		logger.warning('get root_copy file size error:'+str(e))
	return 0

def upload_root_run_data(soa):
	result = 'get source or size error'
	delay,ip = get_transfer_ip_and_delay(soa)
	if delay == 0 and ip == '0.0.0.0':
		delay,ip = get_transfer_ip_and_delay_from_file(soa)
	size = get_root_file_size()
	if delay != 0 and ip != '0.0.0.0' and size != 0:
		result = 'success'

	server = get_server_from_file()

	timestamp = time.strftime('%Y-%m-%d %H:%M:%S')

	root_soa_str_data = dns_id + '|' + root_copy_room_id + '|' + server_id + '|' + server + '|' + ip\
	+ '|' + timestamp + '|' + result + '|' + str(size) + '|' + str(soa) + '|' + str(delay)

	file_name = 'zoneOperation_full_' + dns_id + '_0_' + time.strftime('%Y%m%d%H%M%S') + '.gz'

	logger.info(root_soa_str_data)
	try:
		cache_dir = '/var/drms_toggle_data/'
		with gzip.open(cache_dir + file_name, "wb") as f:
			f.write(bytes(root_soa_str_data, 'utf-8'))
		upload_to_ftp(cache_dir,file_name,'15')
	except Exception as e:
		logger.error('upload root resove data error:'+str(e))

def get_root_copy_soa():
	try:
		dns_query = dns.message.make_query('.', 'SOA')
		res = dns.query.udp(dns_query, '127.0.0.1', port = 53,timeout = 2)
		for i in res.answer:
			for j in i.items:
				return j.serial
	except Exception as e:
		logger.warning('Server exception get soa error:'+str(e))
	return 0

def check_soa_and_upload():
	global loop_count
	now_soa,root_soa = 0,0
	while True:
		if server_type == 'root_copy' and loop_count % 60 == 0:
			now_soa = get_root_copy_soa()
			if now_soa > 0:
				if root_soa != now_soa:
					root_soa = now_soa
					upload_root_run_data(now_soa)
				if loop_count  >= 900 and int(share_delay.value) == 900:
					upload_root_run_data(now_soa)
			else:
				logger.warning('dns server can not work please check')
		if loop_count >= 900:
			loop_count = 0
		sleep(1)
		loop_count += 1

class DrmsToggle(Daemon):
	def run(self):
		logger.info('main process start at: %s' % time.ctime())

		threading._start_new_thread(xgj_main_task,())
		threading._start_new_thread(waj_main_task,())
		check_soa_and_upload()

		logger.info('main process end at: %s' % time.ctime())

if __name__ == '__main__':
	drms_toggle = DrmsToggle('/var/drms_toggle_data/drms_toggle.pid')
	drms_toggle.start()


from __future__ import print_function
import argparse
import torch
import torch.utils.data
from torch import optim
from torch import nn
from torch.utils.data import DataLoader
from gensim.models import KeyedVectors

import os
import numpy as np
from collections import OrderedDict
from multiprocessing import cpu_count

from ptb import PTB
from model import SentenceVAE

parser = argparse.ArgumentParser(description='Sentence VAE Example')

parser.add_argument('--seed', type=int, default=1, metavar='S',
                    help='random seed (default: 1)')
parser.add_argument('--data_dir', type=str, default='data')
parser.add_argument('--create_data', action='store_true')

parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--batch_size', type=int, default=32)

parser.add_argument('--k', type=float, default=0.0025)
parser.add_argument('--x0', type=int, default=2500)
parser.add_argument('--log_interval', type=int, default=50)
parser.add_argument('--save_model_path', type=str, default='model')
parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='enables CUDA training')

args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()

# torch.manual_seed(args.seed)
device = torch.device("cuda" if args.cuda else "cpu")

splits = ['train', 'valid']
datasets = OrderedDict()

for split in splits:
    datasets[split] = PTB(
        data_dir=args.data_dir,
        split=split,
        create_data=args.create_data,
        max_sequence_length=60
    )

# vocab_size = datasets['train'].vocab_size
sos_idx = datasets['train'].sos_idx
eos_idx = datasets['train'].eos_idx
pad_idx = datasets['train'].pad_idx

embedding = KeyedVectors.load('model/pretrained_embedding')
if args.cuda:
    weights = torch.FloatTensor(embedding.syn0).cuda()
else:
    weights = torch.FloatTensor(embedding.syn0)

model = SentenceVAE(weights.size(0), sos_idx, eos_idx, pad_idx, training=True).to(device)

def init_weights(m):
    if type(m) == torch.nn.Linear:
        torch.nn.init.xavier_uniform(m.weight)
        m.bias.data.fill_(0)

model.apply(init_weights)
model.emb = nn.Embedding.from_pretrained(weights)
optimizer = optim.Adam(filter(lambda p: p.requires_grad,model.parameters()),
                       lr=1e-4, weight_decay=1e-3)

def kl_anneal_function(step):
    k = args.k
    x0 = args.x0
    weight = float(1 / (1 + np.exp(-k * (step - x0))))
    return weight

criterion = torch.nn.NLLLoss(size_average=False, ignore_index=pad_idx)

def loss_function(reconx, x, mu, logvar, step):
    # print(torch.argmax(torch.exp(reconx), dim=-1)[0][:50])
    x = x.view(-1).long()
    reconx = reconx.view(-1, reconx.size(2))
    NLL_loss = criterion(reconx, x)
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    beta = kl_anneal_function(step)
    loss = NLL_loss + beta * KLD
    return loss, NLL_loss, KLD, beta

def train(epoch, step):
    model.train()

    data_loader = DataLoader(
        dataset=datasets['train'],
        batch_size=args.batch_size,
        shuffle=True,
        num_workers=cpu_count(),
        pin_memory=torch.cuda.is_available()
    )

    train_loss = 0
    for batch_idx, batch in enumerate(data_loader):
        batch_size = batch['input'].size(0)
        if torch.cuda.is_available():
            batch['input'] = batch['input'].cuda()
            batch['target'] = batch['target'].cuda()
        logp, mu, logvar, z = model(batch['input'])
        loss, NLL_loss, KL_loss, KL_weight = loss_function(logp, batch['target'],
                                                           mu, logvar, step)

        loss = loss / batch_size
        if step == 10:
            checkpoint_path = os.path.join(args.save_model_path,
                                           "model_epoch_%i" % (epoch))
            torch.save(model.state_dict(), checkpoint_path)
            print("Model saved at %s" % checkpoint_path)

        optimizer.zero_grad()
        loss.backward()
        train_loss += loss.item()
        torch.nn.utils.clip_grad_norm(model.parameters(), 5)
        optimizer.step()
        step += 1

        if batch_idx % args.log_interval == 0:
            print('Train Epoch {} [{}/{}] Loss {:.2f} | NLL {:.2f}'
                  ' | KL {:.2f} | Beta {:.3f}'.format(epoch,
                   batch_idx * batch_size, len(data_loader.dataset),
                   loss.item(), NLL_loss.item() / batch_size,
                   KL_loss.item() / batch_size, KL_weight))

    print('====> Epoch: {} Average loss: {:.4f} steps: {}'.format(
          epoch, train_loss * args.batch_size / len(data_loader.dataset), step))

    checkpoint_path = os.path.join(args.save_model_path, "model_epoch_%i" % (epoch))
    torch.save(model.state_dict(), checkpoint_path)
    print("Model saved at %s" % checkpoint_path)
    return step

def test(step):
    model.eval()
    test_loss = 0

    data_loader = DataLoader(
        dataset=datasets['valid'],
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=cpu_count(),
        pin_memory=torch.cuda.is_available()
    )

    with torch.no_grad():
        for batch_index, batch in enumerate(data_loader):
            if torch.cuda.is_available():
                batch['input'] = batch['input'].cuda()
                batch['target'] = batch['target'].cuda()
            logp, mu, logvar, z = model(batch['input'])
            loss, _, _, _ = loss_function(logp, batch['target'],
                                          mu, logvar, step)
            test_loss += loss.item()

    test_loss /= len(data_loader.dataset)
    print('====> Test set loss: {:.4f}'.format(test_loss))

step = 0
for epoch in range(1, args.epochs + 1):
    step = train(epoch, step)
    test(step)


# -*- coding: utf-8 -*-

from django.conf.urls import url

from baremetal_service.bw_views import BmSharedBandwidthsViews, BmSharedBandwidthViews, BmSharedBandwidthFipViews
from baremetal_service.views import BaremetalServiceFloatingIPViews

urlpatterns = [

    # 共享带宽实例管理
    # 功能：购买，列表，编辑，详情，删除/批量删除

    # resource: shared_bandwidths_order
    # 功能：购买
    url(r'^shared_bandwidths_order$', BmSharedBandwidthsViews.as_view(
        actions={'post': 'create'})),

    # resource: shared_bandwidths
    # 功能：列表，编辑，删除/批量删除
    url(r'^shared_bandwidths$', BmSharedBandwidthsViews.as_view(
        actions={'get': 'list', 'put': 'update', 'post': 'destroy'})),

    # resource: shared_bandwidth
    # 功能：搜索详情
    url(r'shared_bandwidth$', BmSharedBandwidthViews.as_view(
        actions={'post': 'search'})),

    # resource: floating IP
    # 功能：添加弹性公网IP，移除弹性公网IP
    url(r'^shared_bandwidth/(?P<bandwidth_id>[0-9a-fA-F-]{1,})/floating_ips$',
        BmSharedBandwidthFipViews.as_view(actions={'get': "list_bandwidth_floatingips"})),
    url(r'^floating_ip/(?P<floating_ip_id>[0-9a-fA-F-]{1,})/shared_bandwidths$',
        BmSharedBandwidthFipViews.as_view(actions={'get': "list_floatingip_bandwidths"})),

    url(r'^shared_bandwidth/(?P<bandwidth_id>[0-9a-fA-F-]{1,})/attach_floating_ips$',
        BmSharedBandwidthFipViews.as_view(actions={'post': 'attach'},
                                          name='bandwidth_attach_floatingips')),

    url(r'^shared_bandwidth/(?P<bandwidth_id>[0-9a-fA-F-]{1,})/detach_floating_ips$',
        BmSharedBandwidthFipViews.as_view(actions={'post': 'detach'},
                                          name='bandwidth_detach_floatingips')),

    # 裸金属平台中涉及的更新：弹性公网IP（floating_ip）
    # 功能：列表，删除
    url(r'^floating_ips$', BaremetalServiceFloatingIPViews.as_view(
        actions={'get': 'floating_ip_list', 'delete': 'floating_ip_delete'})),

]


import feedparser
import datetime
import dateutil.parser
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from django.views import generic
from django_feedparser.settings import *
from .models import Story
from source.models import Sources
from django.utils import timezone
from django.template import loader
from django.db.models.aggregates import Count
from random import randint

def view_stories(request,id):
    num_post = 15
        # adding stories in database
    try:
        rss_url = Sources.objects.get(id=id).rss_text
    except Sources.DoesNotExist:
        alert("Does not Exist")
    feed = feedparser.parse(rss_url)
    for post in Story.objects.all():
        post.delete()

    story_urls = Story.objects.filter(id=id).values_list('url', flat=True).distinct()
    for entry in feed['entries']:
        url = entry.get('link')
        if url not in story_urls:
            story = Story()
            story.title = entry.get('title')
            story.url = url
            date=entry.get('published')
            story.pub_date = dateutil.parser.parse(date)
            body = entry.get('description')
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(body)
            body = soup.get_text()
            story.body_text = body
            story.save()
# passing stories data to template context and render it
    context ={
    "id":id
    }
    return render(request, 'story/story_list.html', context)

def newsfeed(request):
    num_post = 20
    args={}
        # adding stories in database
    query_params = {}
    source_qs = Sources.objects.filter(**query_params).values('rss_text')
    for post in Story.objects.all():
        post.delete()
    for source in source_qs:
        feed = feedparser.parse(source.get('rss_text'))

        story_urls = Story.objects.all().values_list('url', flat=True).distinct()
        for entry in feed['entries']:
                url = entry.get('link')
                if url not in story_urls:
                    story = Story()
                    story.title = entry.get('title')
                    story.url = url
                    date=entry.get('published')
                    story.pub_date = dateutil.parser.parse(date)
                    story.save()
    args['story']=story
    return render(request, 'story/newsfeed.html', args)


"""
Exercise
Convert the program to print all prime numbers to use a function.
Create the function to check if a number is prime or not if needed.

Starting code: tut_09/example_for_all_primes.py
"""

for number in range(1, 100, 2):
    # The number is assumed to be prime
    is_prime = True
    for i in range(2, number):
        if number % i == 0:
            is_prime = False
            break

    # Print result
    if is_prime == True:
        print(number)