# coding=utf-8
# @Author : AYY

import pandas as pd
import numpy as np
from decimal import Decimal, ROUND_HALF_UP
import tools

"""
确定不能买卖的情况
1、当日涨停：不能买入
2、当日跌停：不能卖出
其他：股票停牌...休市
"""

def handle_data():
    df = pd.read_csv('all_data_strategy.csv', encoding='utf-8', skip_blank_lines=True, error_bad_lines=True)
    df.drop(columns=["开盘价", "最高价", "最低价", "成交量", "成交额", "daily_rise_fall"],
            inplace=True)

    df['涨停价'] = df['前收盘价'] * 1.1
    df['跌停价'] = df['前收盘价'] * 0.9

    df['涨停价'] = df['涨停价'].apply(lambda x: float(Decimal(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)))
    df['跌停价'] = df['跌停价'].apply(lambda x: float(Decimal(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)))
    df['recovery_close_price'] = df['recovery_close_price'].apply(
        lambda x: float(Decimal(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)))
    df['short_price_mean'] = df['short_price_mean'].apply(
        lambda x: float(Decimal(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)))
    df['long_price_mean'] = df['long_price_mean'].apply(
        lambda x: float(Decimal(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)))

    """因为采用的是尾盘操作，所以在购买当天，仓位=0，售出当天，仓位=1"""
    buy = df['buy'] & (df['收盘价'] < df['涨停价'])  # 发出购买信号 & 能买，不能买仓位保持和之前一致
    sale = df['sale'] & (df['收盘价'] > df['跌停价'])  # 发出卖出信号 & 能卖， 不能卖仓位保持和之前一致

    df.loc[buy, 'pos'] = 1  # 表示已购买持仓
    df.loc[sale, 'pos'] = 0  # 表示卖出
    df['pos'] = df['pos'].fillna(method='pad', inplace=False)  # 不能买仓位保持和之前一致,不能卖仓位保持和之前一致
    df['pos'] = df['pos'].shift(1)  # 尾盘交易，购买当天不算持仓

    """购买时的购买价格，每次购买成交价 = 上一日收盘价 + 0.1"""
    df['buy_price'] = df['收盘价'].apply(lambda x: float(Decimal(str(x + tools.SLIP_POINT)).quantize(Decimal('0.01'),
                                                                                rounding=ROUND_HALF_UP)))
    df['sale_price'] = df['收盘价'].apply(lambda x: float(Decimal(str(x - tools.SLIP_POINT)).quantize(Decimal('0.01'),
                                                                                rounding=ROUND_HALF_UP)))
    df['buy_price'] = df['buy_price'].shift(1)
    df['sale_price'] = df['sale_price'].shift(1)

    df.to_csv('all_data_buy_sale.csv', index=False)

if __name__ == "__main__":
    handle_data()


#! /usr/bin/python

import sys
import os

myFile = sys.argv[1]
myFO = "tmp.pdb"

myFrames = []
parsing = False

with open(myFile, "r") as f:
    for line in f:
        if "MODEL" in line:
            myFrames.append(line[6:9].strip())

my_identifier = "MODEL %s" % myFrames[-1]

with open(myFO, "w") as fo:

    with open(myFile, "r") as f:

        for line in f:

            if parsing:
                fo.write(line)
                parsing = True

            elif my_identifier == line[:9].strip():
                parsing = True

            else:
                parsing = False

cwd =  os.getcwd()
myDir =  cwd.split("/")[-1]
idx = myDir.find("_")

#cmd = "echo 0 | trjconv -f sampled.pos.pdb -s init.pdb -o tmp.pdb -dump %s"%(myFrames[-1])
#os.system(cmd)
#os.system("tail -n +4 tmp.pdb > tmp2.pdb")
os.system("sed -i.old '1s;^;CBLC >AB\\n;' tmp.pdb")
os.system("mv tmp.pdb ../my_structures_ctd/init%s.pdb" % myDir[idx:])
#os.system("rm tmp*")


from unittest.mock import AsyncMock

import pytest

from shared.models.webhook_topics.base import CloudApiWebhookEventGeneric
from webhooks.dependencies.redis_service import RedisService

wallet_id = "test_wallet"
topic = "test_topic"
payload = '"payload": {"test":"1"}'

json_entries = [
    f'{{"wallet_id": "{wallet_id}", "topic": "{topic}", "origin": "a", {payload}}}',
    f'{{"wallet_id": "{wallet_id}", "topic": "{topic}", "origin": "a", {payload}}}',
]
cloudapi_entries = [
    CloudApiWebhookEventGeneric(
        wallet_id=wallet_id, topic=topic, origin="a", payload={"test": "1"}
    ),
    CloudApiWebhookEventGeneric(
        wallet_id=wallet_id, topic=topic, origin="a", payload={"test": "1"}
    ),
]

@pytest.mark.anyio
async def test_add_webhook_event():
    event_json = json_entries[0]

    # Create a mock Redis client with the methods you want to test
    redis_client = AsyncMock()
    redis_client.zadd = AsyncMock()
    redis_client.publish = AsyncMock()

    # Initialize RedisService with the mocked Redis client
    redis_service = RedisService(redis_client)

    # Call the method you want to test
    await redis_service.add_webhook_event(event_json, wallet_id)

    # Assert that the mocked methods were called as expected
    redis_client.zadd.assert_called_once()
    redis_client.publish.assert_called_once()

@pytest.mark.anyio
async def test_get_json_webhook_events_by_wallet():
    redis_client = AsyncMock()
    redis_client.zrange = AsyncMock(return_value=[e.encode() for e in json_entries])
    redis_service = RedisService(redis_client)

    events = await redis_service.get_json_webhook_events_by_wallet(wallet_id)

    assert events == json_entries
    redis_client.zrange.assert_called_once()

@pytest.mark.anyio
async def test_get_webhook_events_by_wallet(mocker):
    expected_events = cloudapi_entries

    redis_service = RedisService(AsyncMock())
    mocker.patch.object(
        redis_service, "get_json_webhook_events_by_wallet", return_value=json_entries
    )
    mocker.patch(
        "shared.util.rich_parsing.parse_with_error_handling",
        side_effect=expected_events,
    )

    events = await redis_service.get_webhook_events_by_wallet(wallet_id)

    assert events == expected_events

@pytest.mark.anyio
async def test_get_json_webhook_events_by_wallet_and_topic(mocker):
    different_json = [
        '{"payload":{"test":"1"},"topic":"test_topic"}',
        '{"payload":{"test":"2"},"topic":"other_topic"}',
    ]
    expected_events = ['{"payload":{"test":"1"},"topic":"test_topic"}']

    redis_service = RedisService(AsyncMock())
    mocker.patch.object(
        redis_service, "get_json_webhook_events_by_wallet", return_value=different_json
    )

    events = await redis_service.get_json_webhook_events_by_wallet_and_topic(
        wallet_id="test_wallet_id", topic=topic
    )

    assert events == expected_events

@pytest.mark.anyio
async def test_get_webhook_events_by_wallet_and_topic(mocker):
    event_instances = [
        CloudApiWebhookEventGeneric(
            wallet_id=wallet_id, topic=topic, origin="a", payload={"test": "1"}
        ),
        CloudApiWebhookEventGeneric(
            wallet_id=wallet_id, topic="other", origin="a", payload={"test": "2"}
        ),
    ]
    expected_events = [event_instances[0]]

    redis_service = RedisService(AsyncMock())
    mocker.patch.object(
        redis_service, "get_webhook_events_by_wallet", return_value=event_instances
    )

    events = await redis_service.get_webhook_events_by_wallet_and_topic(
        wallet_id, topic
    )

    assert events == expected_events

@pytest.mark.anyio
async def test_get_json_events_by_timestamp():
    start_timestamp = 1609459200
    end_timestamp = 1609545600

    redis_client = AsyncMock()
    redis_client.zrangebyscore = AsyncMock(
        return_value=[e.encode() for e in json_entries]
    )

    redis_service = RedisService(redis_client)

    events = await redis_service.get_json_events_by_timestamp(
        wallet_id, start_timestamp, end_timestamp
    )

    assert events == json_entries
    redis_client.zrangebyscore.assert_called_once_with(
        f"wallet_id:{wallet_id}", min=start_timestamp, max=end_timestamp
    )

@pytest.mark.anyio
async def test_get_events_by_timestamp(mocker):
    start_timestamp = 1609459200
    end_timestamp = 1609545600

    redis_service = RedisService(AsyncMock())
    mocker.patch.object(
        redis_service, "get_json_events_by_timestamp", return_value=json_entries
    )
    mocker.patch(
        "shared.util.rich_parsing.parse_with_error_handling",
        side_effect=cloudapi_entries,
    )

    events = await redis_service.get_events_by_timestamp(
        wallet_id, start_timestamp, end_timestamp
    )

    assert events == cloudapi_entries

@pytest.mark.anyio
async def test_get_all_wallet_ids():
    expected_wallet_ids = ["wallet1", "wallet2", "wallet3"]
    scan_results = [
        (
            1,
            [
                f"wallet_id:{wallet_id}".encode()
                for wallet_id in expected_wallet_ids[:2]
            ],
        ),
        (0, [f"wallet_id:{expected_wallet_ids[2]}".encode()]),
    ]

    redis_client = AsyncMock()
    redis_client.scan = AsyncMock(side_effect=scan_results)

    redis_service = RedisService(redis_client)

    wallet_ids = await redis_service.get_all_wallet_ids()

    assert set(wallet_ids) == set(expected_wallet_ids)
    assert redis_client.scan.call_count == 2


from io import StringIO

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.auth.decorators import permission_required, login_required
from django.utils.translation import gettext as _
from django.contrib import messages
from django.core.management import call_command
from django.db.models import Q, Count
from django.views.generic.edit import CreateView, UpdateView

from bootstrap_modal_forms.generic import BSModalCreateView, BSModalUpdateView, BSModalFormView
from utils.django.urls import reverse, reverse_lazy, http_referer

from dashboard.forms import ParaErrorList
from reman.models import Repair, SparePart, Batch, EcuModel, Default, EcuType, EcuRefBase
from reman.forms import (
    CheckOutRepairForm, DefaultForm, PartEcuTypeForm, PartSparePartForm, EcuModelForm, CheckOutSelectBatchForm,
    StockSelectBatchForm, EcuDumpModelForm, EcuTypeForm, RefRemanForm
)

context = {
    'title': 'Reman'
}

"""
~~~~~~~~~~~~~~
MANAGER VIEWS
~~~~~~~~~~~~~~
"""

@permission_required('reman.change_ecumodel')
def ref_base_edit(request, barcode):
    next_form = int(request.GET.get('next', 0))
    if next_form == 1:
        card_title = "Edit Type ECU"
        try:
            ecu_type = EcuType.objects.get(ecumodel__barcode=barcode)
            form = PartEcuTypeForm(request.POST or None, error_class=ParaErrorList, instance=ecu_type)
        except EcuType.DoesNotExist:
            form = PartEcuTypeForm(request.POST or None, error_class=ParaErrorList)
    elif next_form == 2:
        card_title = "Edit Pièce détachée"
        ecu_type = get_object_or_404(EcuType, ecumodel__barcode=barcode)
        try:
            part = SparePart.objects.get(ecutype__ecumodel__barcode=barcode)
            form = PartSparePartForm(request.POST or None, error_class=ParaErrorList, instance=part)
        except SparePart.DoesNotExist:
            form = PartSparePartForm(request.POST or None, error_class=ParaErrorList)
            form.initial['code_produit'] = ecu_type.part_name()
        if form.is_valid():
            part_obj = form.save()
            ecu_type.spare_part = part_obj
            ecu_type.save()
            ecu = get_object_or_404(EcuModel, barcode=barcode)
            context.update(locals())
            return render(request, 'reman/part/part_full_detail.html', context)
    else:
        card_title = "Edit Modèle ECU"
        model = get_object_or_404(EcuModel, barcode=barcode)
        form = EcuModelForm(request.POST or None, error_class=ParaErrorList, instance=model)
        form.initial['hw_reference'] = model.ecu_type.hw_reference
    if request.POST and form.is_valid():
        form.save()
        next_form += 1
        return redirect(reverse('reman:edit_ref_base', kwargs={'barcode': barcode}) + '?next=' + str(next_form))
    context.update(locals())
    return render(request, 'reman/ecu_ref_base_update.html', context)

class RefRemanCreateView(PermissionRequiredMixin, BSModalCreateView):
    """ View of modal default create """
    permission_required = 'reman.add_ecurefbase'
    template_name = 'reman/modal/ref_reman_create.html'
    form_class = RefRemanForm
    success_message = _('Success: Reman reference was created.')
    success_url = reverse_lazy('reman:base_ref_table')

    def get_initial(self):
        initial = super().get_initial()
        ecu_dict = EcuRefBase.objects.filter(reman_reference=self.request.GET.get('ref', None)).values().first()
        if ecu_dict:
            for field, value in ecu_dict.items():
                if field not in ['reman_reference']:
                    initial[field] = value
                if field == 'ecu_type_id' and value is not None:
                    initial['hw_reference'] = EcuType.objects.get(pk=value).hw_reference
        return initial

class RefRemanUpdateView(PermissionRequiredMixin, BSModalUpdateView):
    """ View of modal ECU Hardware update """
    model = EcuRefBase
    permission_required = 'reman.change_ecurefbase'
    template_name = 'reman/modal/ref_reman_update.html'
    form_class = RefRemanForm
    success_message = _('Success: Reman reference was updated.')
    success_url = reverse_lazy('reman:base_ref_table')

class DefaultCreateView(PermissionRequiredMixin, CreateView):
    """ View of modal default create """
    permission_required = 'reman.add_default'
    template_name = 'reman/default_form.html'
    form_class = DefaultForm
    success_message = _('Success: Reman Default was created.')
    success_url = reverse_lazy('reman:default_table')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "Reman"
        context['card_title'] = _('Create Default')
        return context

class DefaultUpdateView(PermissionRequiredMixin, UpdateView):
    """ View of modal default update """
    model = Default
    permission_required = 'reman.change_default'
    template_name = 'reman/default_form.html'
    form_class = DefaultForm
    success_message = _('Success: Reman Default was updated.')
    success_url = reverse_lazy('reman:default_table')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "Reman"
        context['card_title'] = _('Update Default')
        return context

"""
~~~~~~~~~~~~~~~
IN / OUT VIEWS
~~~~~~~~~~~~~~~
"""

class CheckOutFilterView(PermissionRequiredMixin, BSModalFormView):
    template_name = 'reman/modal/batch_select.html'

    def get_form_class(self):
        select = self.request.GET.get('select', None)
        if select == "stock":
            return StockSelectBatchForm
        return CheckOutSelectBatchForm

    def has_permission(self):
        user = self.request.user
        return user.has_perm('reman.stock_repair') or user.has_perm('reman.close_repair')

    def form_valid(self, form):
        self.filter = '?filter=' + str(form.cleaned_data['batch'])
        return super().form_valid(form)

    def get_success_url(self):
        return reverse_lazy('reman:out_table') + self.filter

# @permission_required('reman.close_repair')
@login_required()
def out_table(request):
    """ View of Reman Out Repair table page """
    batch_number = request.GET.get('filter')
    table_title = 'Préparation lot n° {}'.format(batch_number)
    repaired = Count('repairs', filter=Q(repairs__status="Réparé", repairs__quality_control=True))
    packed = Count('repairs', filter=Q(repairs__checkout=True))
    batch = Batch.objects.filter(batch_number=batch_number).annotate(repaired=repaired, packed=packed).first()
    files = Repair.objects.filter(
        batch__batch_number=batch_number, status="Réparé", checkout=False, quality_control=True
    )
    form = CheckOutRepairForm(request.POST or None, error_class=ParaErrorList, batch_number=batch_number, )
    if request.POST and form.is_valid():
        repair = form.save()
        messages.success(request, _('Repair n°%(repair)s to batch n°%(batch)s ready for shipment') % {
            'repair': repair.identify_number,
            'batch': repair.batch})
        form = CheckOutRepairForm(error_class=ParaErrorList)
    errors = form.errors.items()
    context.update(locals())
    return render(request, 'reman/repair/out_table.html', context)

"""
~~~~~~~~~~~~~~~~~
CONSULTING VIEWS
~~~~~~~~~~~~~~~~~
"""

@permission_required('reman.view_ecurefbase')
def base_ref_table(request):
    """ View of EcuRefBase table page """
    if request.GET.get('customer', None) == "volvo":
        title = "Reman VOLVO"
        refs = EcuRefBase.objects.filter(brand__in=['VOLVO', 'RENAULT'])
        return render(request, 'reman/ref/sem_ref_table.html', locals())
    title = "Reman PSA"
    refs = EcuRefBase.objects.exclude(brand__in=['VOLVO', 'RENAULT'])
    return render(request, 'reman/ref/base_ref_table.html', locals())

@login_required()
def ecu_hw_table(request):
    """ View of EcuType table page """
    if request.GET.get('customer', None) == "volvo":
        title = "Reman VOLVO"
        ecus = EcuType.objects.filter(technical_data="SEM")
        return render(request, 'reman/ref/sem_hw_table.html', locals())
    title = "Reman PSA"
    table_title = 'Référence Hardware'
    ecus = EcuType.objects.exclude(technical_data="SEM")
    return render(request, 'reman/ref/ecu_hw_table.html', locals())

@login_required
def ecu_hw_generate(request):
    """ Generating Scan IN/OU EXCEL files """
    out = StringIO()
    call_command("exportreman", "--scan_in_out", stdout=out)
    if "Export error" in out.getvalue():
        for msg in out.getvalue().split('\n'):
            if "Export error" in msg:
                messages.warning(request, msg)
    else:
        messages.success(request, "Exportation Scan IN/OUT terminée.")
    return redirect('reman:ecu_hw_table')

class EcuHwCreateView(PermissionRequiredMixin, BSModalCreateView):
    """ View of modal ECU Hardware update """
    permission_required = 'reman.add_ecutype'
    template_name = 'reman/modal/ecu_hw_create.html'
    form_class = EcuTypeForm
    success_message = _('Success: Reman ECU HW Reference was created.')

    def get_initial(self):
        initial = super().get_initial()
        ecu_dict = EcuType.objects.filter(hw_reference=self.request.GET.get('hw', None)).values().first()
        if ecu_dict:
            for field, value in ecu_dict.items():
                if field not in ['hw_reference']:
                    initial[field] = value
        return initial

    def get_success_url(self):
        return http_referer(self.request)

class EcuHwUpdateView(PermissionRequiredMixin, BSModalUpdateView):
    """ View of modal ECU Hardware update """
    model = EcuType
    permission_required = 'reman.change_ecutype'
    template_name = 'reman/modal/ecu_hw_update.html'
    form_class = EcuTypeForm
    success_message = _('Success: Reman ECU HW Reference was updated.')
    success_url = reverse_lazy('reman:ecu_hw_table')

@login_required()
def ecu_dump_table(request):
    table_title = 'Dump à réaliser'
    ecus = EcuModel.objects.filter(to_dump=True)
    context.update(locals())
    return render(request, 'reman/ecu_dump_table.html', context)

class EcuDumpUpdateView(PermissionRequiredMixin, BSModalUpdateView):
    """ View of modal ECU Dump update """
    model = EcuModel
    permission_required = 'reman.change_ecumodel'
    template_name = 'reman/modal/ecu_dump_update.html'
    form_class = EcuDumpModelForm
    success_message = _('Success: Reman ECU dump was updated.')
    success_url = reverse_lazy('reman:ecu_dump_table')

@permission_required('reman.view_default')
def default_table(request):
    table_title = 'Liste de panne'
    defaults = Default.objects.all()
    context.update(locals())
    return render(request, 'reman/default_table.html', context)


from codepack import CodePack, CodePackSnapshot, ArgPack
from fastapi import APIRouter, HTTPException
from ..models.scheduler import CodePackIDJob, CodePackJSONJob, SnapshotJSONJob, IDPairJob
from apscheduler.jobstores.base import JobLookupError, ConflictingIdError
from ..dependencies import common

router = APIRouter(
    prefix='/scheduler',
    tags=['scheduler'],
    responses={404: {'description': 'Not Found'},
               409: {'description': 'Conflict'}},
)

@router.post('/register')
async def register(params: CodePackJSONJob):
    codepack = CodePack.from_dict(params.codepack)
    argpack = ArgPack.from_dict(params.argpack)
    try:
        common.scheduler.add_codepack(codepack=codepack, argpack=argpack, job_id=params.job_id,
                                      trigger=params.trigger, **params.trigger_config)
    except ConflictingIdError:
        _job_id = params.job_id if params.job_id else codepack.id
        raise HTTPException(status_code=409, detail='%s already exists' % _job_id)
    return {'serial_number': codepack.serial_number}

@router.post('/register/id')
async def register_by_id(params: CodePackIDJob):
    codepack = CodePack.load(params.id)
    if codepack is None:
        raise HTTPException(status_code=404, detail="'%s' not found" % params.id)
    argpack = ArgPack.from_dict(params.argpack)
    try:
        common.scheduler.add_codepack(codepack=codepack, argpack=argpack, job_id=params.job_id,
                                      trigger=params.trigger, **params.trigger_config)
    except ConflictingIdError:
        _job_id = params.job_id if params.job_id else codepack.id
        raise HTTPException(status_code=409, detail='%s already exists' % _job_id)
    return {'serial_number': codepack.serial_number}

@router.post('/register/id-pair')
async def register_by_id_pair(params: IDPairJob):
    codepack = CodePack.load(params.codepack_id)
    if codepack is None:
        raise HTTPException(status_code=404, detail="'%s' not found" % params.codepack_id)
    argpack = ArgPack.load(params.argpack_id)
    if argpack is None:
        raise HTTPException(status_code=404, detail="'%s' not found" % params.argpack_id)
    try:
        common.scheduler.add_codepack(codepack=codepack, argpack=argpack, job_id=params.job_id,
                                      trigger=params.trigger, **params.trigger_config)
    except ConflictingIdError:
        _job_id = params.job_id if params.job_id else codepack.id
        raise HTTPException(status_code=409, detail='%s already exists' % _job_id)
    return {'serial_number': codepack.serial_number}

@router.post('/register/snapshot')
async def register_by_snapshot(params: SnapshotJSONJob):
    snapshot = CodePackSnapshot.from_dict(params.snapshot)
    try:
        common.scheduler.add_codepack(snapshot=snapshot, job_id=params.job_id,
                                      trigger=params.trigger, **params.trigger_config)
    except ConflictingIdError:
        _job_id = params.job_id if params.job_id else snapshot.id
        raise HTTPException(status_code=409, detail='%s already exists' % _job_id)
    return {'serial_number': snapshot.serial_number}

@router.delete('/unregister/{id}')
async def unregister(id: str):
    try:
        common.scheduler.remove_job(job_id=id)
    except JobLookupError:
        raise HTTPException(status_code=404, detail='%s not found' % id)
    return {'id': id}

@router.get('/alive')
async def alive():
    is_alive = common.scheduler.is_running()
    return {'alive': is_alive}


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

import pickle

#policy network
class actor_netw(tf.keras.Model):

    def __init__(self,num_states, actor_hidden_units, num_actions, action_high):
        super(actor_netw,self).__init__()

        self.action_high = action_high

        self.actor_input_layer = tf.keras.layers.InputLayer(input_shape=(num_states,))

        self.actor_hidden_layers = []

        for i in actor_hidden_units:
            self.actor_hidden_layers.append(
                    tf.keras.layers.Dense(i, activation= tf.nn.leaky_relu, kernel_initializer= 'RandomNormal'))

        self.actor_output_layer = tf.keras.layers.Dense(num_actions, activation= 'tanh', kernel_initializer= 'RandomNormal')

    @tf.function
    def call(self,inputs):

        z = self.actor_input_layer(inputs)

        for layer in self.actor_hidden_layers:
            z = layer(z)
        output = self.actor_output_layer(z)*self.action_high

        return output

#q network
class critic_netw(tf.keras.Model):

    def __init__(self,num_states, critic_hidden_units, num_actions):
        super(critic_netw,self).__init__()

        #Q1
        self.critic1_input_layer = tf.keras.layers.InputLayer(input_shape=(num_states + num_actions,))

        self.critic1_hidden_layers = []

        for j in critic_hidden_units:
            self.critic1_hidden_layers.append(
                    tf.keras.layers.Dense(j, activation= tf.nn.leaky_relu, kernel_initializer= 'RandomNormal'))

        self.critic1_output_layer = tf.keras.layers.Dense(1, activation= 'linear', kernel_initializer= 'RandomNormal')

        #Q2
        self.critic2_input_layer = tf.keras.layers.InputLayer(input_shape=(num_states + num_actions,))

        self.critic2_hidden_layers = []

        for j in critic_hidden_units:
            self.critic2_hidden_layers.append(
                    tf.keras.layers.Dense(j, activation= tf.nn.leaky_relu, kernel_initializer= 'RandomNormal'))

        self.critic2_output_layer = tf.keras.layers.Dense(1, activation= 'linear', kernel_initializer= 'RandomNormal')

    @tf.function
    def call(self,input_state,input_action):

        inputs=tf.concat((input_state,input_action),1)

        #Q1
        z1 = self.critic1_input_layer(inputs)

        for layer in self.critic1_hidden_layers:
            z1 = layer(z1)

        output_c1 = self.critic1_output_layer(z1)

        #Q2
        z2 = self.critic2_input_layer(inputs)

        for layer in self.critic2_hidden_layers:
            z2 = layer(z2)

        output_c2 = self.critic2_output_layer(z2)

        return output_c1, output_c2

class TD3_Agent:

    def __init__(self,num_states, actor_hidden_units, critic_hidden_units, num_actions,
                 action_low, action_high, gamma, eta_critic, eta_actor, soft_tau,
                 batch_size, cap_buffer, gauss_reg, clip_reg, delayed_train,
                 train_after, train_every, gradient_steps):

        self.num_states=num_states
        self.num_actions=num_actions
        self.action_low=action_low
        self.action_high=action_high

        self.gamma=gamma
        self.critic_optimizer = tf.optimizers.Adam(eta_critic)
        self.actor_optimizer = tf.optimizers.Adam(eta_actor)
        self.batch_size=batch_size
        self.soft_tau = soft_tau

        self.gauss_reg = gauss_reg
        self.clip_reg = clip_reg
        self.delayed_train = delayed_train

        self.train_after = train_after
        self.train_every = train_every
        self.gradient_steps = gradient_steps

        self.history = {'Tot_Rew':[], 'Avg_Rew':[]}
        self.rep_buffer = {'s':[],'a':[],'r':[],'sn':[],'done':[]}
        self.cap_buffer = cap_buffer

        self.actor_train=actor_netw(num_states, actor_hidden_units, num_actions, action_high)
        self.actor_target=actor_netw(num_states, actor_hidden_units, num_actions, action_high)
        self.actor_target.trainable=False

        self.critic_train=critic_netw(num_states, critic_hidden_units, num_actions)
        self.critic_target=critic_netw(num_states, critic_hidden_units, num_actions)
        self.critic_target.trainable=False

    def action_selection(self,state,gauss_scale):

        noise=np.float32(np.random.normal(0,gauss_scale,self.num_actions))
        action=self.actor_train(np.asarray([state],dtype=np.float32))

        action=np.reshape(action,self.num_actions) + noise
        action=np.clip(action,np.float32(self.action_low),np.float32(self.action_high))

        return action.tolist()

    def fill_replay_buff(self, state, action, reward, next_state, done, step, max_steps):
        #Avoid confuising a final state in an episode trajectory with the terminal state
        if done and step < max_steps:
            done_dummy =  True
        else:
            done_dummy = False

        experience = {'s':state,'a':action,'r':reward,'sn':next_state,'done':done_dummy}

        if len(self.rep_buffer['s']) == self.cap_buffer:
            for key in self.rep_buffer.keys():
                self.rep_buffer[key].pop(0)
        for key, value in experience.items():
            self.rep_buffer[key].append(value)

    def fill_history(self,T_Rew):

        T_Rew = np.float32(T_Rew)
        if len(self.history['Tot_Rew']) >= 50:
            avg_rew = sum(self.history['Tot_Rew'][-50:])/50
            avg_rew = np.float32(avg_rew)
        else:
            avg_rew = None

        self.history['Tot_Rew'].append(T_Rew)
        self.history['Avg_Rew'].append(avg_rew)

    def init_weights(self):

        self.critic_train(np.ones([1,self.num_states],dtype=np.float32),np.ones([1,self.num_actions],dtype=np.float32))
        self.critic_target(np.ones([1,self.num_states],dtype=np.float32),np.ones([1,self.num_actions],dtype=np.float32))

        self.actor_train(np.ones([1,self.num_states],dtype=np.float32))
        self.actor_target(np.ones([1,self.num_states],dtype=np.float32))

        critic_train_variables = np.array(self.critic_train.weights, dtype=object)
        actor_train_variables = np.array(self.actor_train.weights, dtype=object)

        critic_targ_variables = np.array(self.critic_target.weights, dtype=object)
        actor_targ_variables = np.array(self.actor_target.weights, dtype=object)

        for c_train, c_targ in zip(critic_train_variables,critic_targ_variables):
            c_targ.assign(c_train.numpy())

        for a_train, a_targ in zip(actor_train_variables,actor_targ_variables):
            a_targ.assign(a_train.numpy())

    def _copy_weights(self,soft_tau):
        critic_train_variables = np.array(self.critic_train.weights, dtype=object)
        actor_train_variables = np.array(self.actor_train.weights, dtype=object)

        critic_targ_variables = np.array(self.critic_target.weights, dtype=object)
        actor_targ_variables = np.array(self.actor_target.weights, dtype=object)

        #Soft update
        soft_critic_update= soft_tau*critic_train_variables + (1-soft_tau)*critic_targ_variables
        soft_actor_update= soft_tau*actor_train_variables + (1-soft_tau)*actor_targ_variables

        for c_soft, c_targ in zip(soft_critic_update,critic_targ_variables):
            c_targ.assign(c_soft.numpy())

        for a_soft, a_targ in zip(soft_actor_update,actor_targ_variables):
            a_targ.assign(a_soft.numpy())

    def train(self, t):

        if t >= self.train_after and t % self.train_every == 0:

            for j in range(self.gradient_steps):

                ids = np.random.randint(low=0,high=len(self.rep_buffer['s']), size=self.batch_size)
                states = np.asarray([self.rep_buffer['s'][i] for i in ids],dtype=np.float32)
                actions = np.asarray([self.rep_buffer['a'][i] for i in ids],dtype=np.float32)
                rewards = np.asarray([[self.rep_buffer['r'][i]] for i in ids],dtype=np.float32)
                next_states = np.asarray([self.rep_buffer['sn'][i] for i in ids],dtype=np.float32)
                dones = np.asarray([[self.rep_buffer['done'][i]] for i in ids])

                #Target Policy Smoothing
                noise_reg=np.clip(np.float32(np.random.normal(0,self.gauss_reg,[self.batch_size,self.num_actions])),
                                  -self.clip_reg,self.clip_reg)
                action_target= np.clip(self.actor_target(next_states)+noise_reg,
                                       np.float32(self.action_low),np.float32(self.action_high))

                #Clipped Double-Q Learning
                Q1_target, Q2_target = self.critic_target(next_states,action_target)

                y=np.where(dones,rewards,
                           rewards + self.gamma*np.minimum(Q1_target,Q2_target))

                with tf.GradientTape() as tape1, tf.GradientTape() as tape2:

                    Q1_train, Q2_train = self.critic_train(states,actions)

                    critic1_loss = tf.math.reduce_sum(tf.math.square(y - Q1_train))
                    critic2_loss = tf.math.reduce_sum(tf.math.square(y - Q2_train))
                    #critic_loss = critic1_loss + critic2_loss

                    critic_variables= self.critic_train.trainable_variables

                    critic1_gradients= tape1.gradient(critic1_loss,critic_variables)
                    self.critic_optimizer.apply_gradients(zip(critic1_gradients,critic_variables))

                    critic2_gradients= tape2.gradient(critic2_loss,critic_variables)
                    self.critic_optimizer.apply_gradients(zip(critic2_gradients,critic_variables))

                #Delayed Policy Updates
                if j % self.delayed_train == 0:

                    with tf.GradientTape() as tape:

                        action_next=self.actor_train(states)
                        Q1_train_n, _ = self.critic_train(states,action_next)

                        actor_loss= -tf.math.reduce_mean(Q1_train_n)

                        actor_variables= self.actor_train.trainable_variables
                        actor_gradients= tape.gradient(actor_loss,actor_variables)
                        self.actor_optimizer.apply_gradients(zip(actor_gradients,actor_variables))

                    self._copy_weights(self.soft_tau)

        #return critic_loss, actor_loss

    def plot_results(self):
        plt.figure()
        plt.plot(self.history['Tot_Rew'],'o' ,markerfacecolor='white', label="Episode Reward")
        plt.plot(self.history['Avg_Rew'], label="Average Reward")
        plt.grid()
        plt.xlabel('Episodes')
        plt.ylabel('Total Reward')
        plt.legend()

    def save_history(self, file_name):
        #File name should be "file_name.data"

        with open(file_name, 'wb') as filehandle:

            pickle.dump(self.history, filehandle)

def load_history(file_name):
    with open(file_name, 'rb') as filehandle:
    # read the data as binary data stream
        history = pickle.load(filehandle)

    plt.figure()
    plt.plot(history['Tot_Rew'],'o' ,markerfacecolor='white', label="Episode Reward")
    plt.plot(history['Avg_Rew'], label="Average Reward")
    plt.grid()
    plt.xlabel('Episodes')
    plt.ylabel('Total Reward')
    plt.legend()


import numpy as np
#
TYPE,LON,LAT,HGT,RMSA,RMSF,OBS_VAL,OBS_PR,OBS_PO,PRI,POS,PRI_ES,POS_ES,T_SPP,T_SPO =  np.loadtxt('fort.FORTNO',skiprows=0, usecols=range(0,15), unpack=True)
output1 = open('ERRTOT.txt', "w+")
output2 = open('ERRNH.txt', "w+")
output3 = open('ERRSH.txt', "w+")
output4 = open('ERREQ.txt', "w+")
print(LON)
if(len(LON)<3):
   output1.write("%12s %12s %12s %12s %12s %12s %12s %12s %12s %12s %12s \n" % (("nan","nan","nan","nan","nan","nan","nan","nan","nan","nan","nan")))
   output2.write("%12s %12s %12s %12s %12s %12s %12s %12s %12s %12s %12s \n" % (("nan","nan","nan","nan","nan","nan","nan","nan","nan","nan","nan")))
   output3.write("%12s %12s %12s %12s %12s %12s %12s %12s %12s %12s %12s \n" % (("nan","nan","nan","nan","nan","nan","nan","nan","nan","nan","nan")))
   output4.write("%12s %12s %12s %12s %12s %12s %12s %12s %12s %12s %12s \n" % (("nan","nan","nan","nan","nan","nan","nan","nan","nan","nan","nan")))
   output1.close()
   output2.close()
   output3.close()
   output4.close()
   quit()
#
del TYPE,LON,LAT,HGT,RMSA,RMSF,OBS_VAL,OBS_PR,OBS_PO,PRI,POS,PRI_ES,POS_ES,T_SPP,T_SPO
#
TYPE,LON,LAT,HGT,RMSA,RMSF,OBS_VAL,OBS_PR,OBS_PO,PRI,POS,PRI_ES,POS_ES,T_SPP,T_SPO =  np.loadtxt('fort.FORTNO',skiprows=2, usecols=range(0,15), unpack=True)
#
nobs=len(LON)
E_PO=OBS_VAL-OBS_PO
E_PR=OBS_VAL-OBS_PR
NH=0;EQ=0;SH=0
E_PONH=0.0;E_PRNH=0.0;RMSANH=0.0;RMSFNH=0.0
PRI_ESNH=0.0;POS_ESNH=0.0
PRINH=0.0;POSNH=0.0
TPRNH=0.0;TPONH=0.0
#
E_POSH=0.0;E_PRSH=0.0;RMSASH=0.0;RMSFSH=0.0
PRI_ESSH=0.0;POS_ESSH=0.0
PRISH=0.0;POSSH=0.0
TPRSH=0.0;TPOSH=0.0
#
E_POEQ=0.0;E_PREQ=0.0;RMSAEQ=0.0;RMSFEQ=0.0
PRI_ESEQ=0.0;POS_ESEQ=0.0
PRIEQ=0.0;POSEQ=0.0
TPREQ=0.0;TPOEQ=0.0
#
for i in range(0,nobs):
   if(LAT[i]>30.0):
      E_PONH=E_PONH+E_PO[i];E_PRNH=E_PRNH+E_PR[i]
      RMSANH=RMSANH+RMSA[i];RMSFNH=RMSFNH+RMSF[i]
      PRI_ESNH=PRI_ESNH+PRI_ES[i];POS_ESNH=POS_ESNH+POS_ES[i]
      PRINH=PRINH+PRI[i];POSNH=POSNH+POS[i]
      TPRNH=TPRNH+T_SPP[i];TPONH=TPONH+T_SPO[i]
      NH=NH+1
#
   if(LAT[i]<-30.0):
      E_POSH=E_POSH+E_PO[i];E_PRSH=E_PRSH+E_PR[i]
      RMSASH=RMSASH+RMSA[i];RMSFSH=RMSFSH+RMSF[i]
      PRI_ESSH=PRI_ESSH+PRI_ES[i];POS_ESSH=POS_ESSH+POS_ES[i]
      PRISH=PRISH+PRI[i];POSSH=POSSH+POS[i]
      TPRSH=TPRSH+T_SPP[i];TPOSH=TPOSH+T_SPO[i]
      SH=SH+1
#
   if(LAT[i]<=30.0 and LAT[i]>=-30.0):
      E_POEQ=E_POEQ+E_PO[i];E_PREQ=E_PREQ+E_PR[i]
      RMSAEQ=RMSAEQ+RMSA[i];RMSFEQ=RMSFEQ+RMSF[i]
      PRI_ESEQ=PRI_ESEQ+PRI_ES[i];POS_ESEQ=POS_ESEQ+POS_ES[i]
      PRIEQ=PRIEQ+PRI[i];POSEQ=POSEQ+POS[i]
      TPREQ=TPREQ+T_SPP[i];TPOEQ=TPOEQ+T_SPO[i]
      EQ=EQ+1
#
output1.write("%12.0f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f \n" % (nobs,np.average(E_PO),np.average(E_PR),np.average(RMSA),np.average(RMSF),np.average(POS_ES),np.average(PRI_ES),np.average(POS),np.average(PRI),np.average(T_SPP),np.average(T_SPO)))
output2.write("%12.0f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f \n" % (NH,E_PONH/NH,E_PRNH/NH,RMSANH/NH,RMSFNH/NH,POS_ESNH/NH,PRI_ESNH/NH,POSNH/NH,PRINH/NH,TPRNH/NH,TPONH/NH))
output3.write("%12.0f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f \n" % (SH,E_POSH/SH,E_PRSH/SH,RMSASH/SH,RMSFSH/SH,POS_ESSH/SH,PRI_ESSH/SH,POSSH/SH,PRISH/SH,TPRSH/SH,TPOSH/SH))
output4.write("%12.0f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f \n" % (EQ,E_POEQ/EQ,E_PREQ/EQ,RMSAEQ/EQ,RMSFEQ/EQ,POS_ESEQ/EQ,PRI_ESEQ/EQ,POSEQ/EQ,PRIEQ/EQ,TPREQ/EQ,TPOEQ/EQ))
output1.close()
output2.close()
output3.close()
output4.close()
quit()


#prompt user to enter the start path and file name, search recursively for the given
#file name starting at the given path, when file is found, display the full path to the file.

import os

def search(filename):
	startpath='C:\\Users'
	for root, dirs, files in os.walk(startpath):
		if filename in files:
			print(root,filename)
	print("Done!!!")
	input()
try:
	name=input("filename:")
	search(name)
except:
	print("Error")


# -*- coding: cp1252 -*-
# Analysoitavat GPS-tiedostot csv:ksi #
# http://gis.stackexchange.com/questions/109008/python-script-to-export-csv-tables-from-gdb

import arcpy
import os
import csv

# Määritetään päähakemisto
ws_dir = r"[dir_fp]"
# GPS-pisteiden hakemisto
GPS_fp = os.path.join(ws_dir,"GPS_pisteet.gdb")

# Haetaan reittipistetiedostot ja listataan ne
arcpy.env.workspace = GPS_fp
# Listataan GPS-pisteet omista dataseteistaan
analyysiList = arcpy.ListFeatureClasses("","","Analyysipisteet") # analyysipisteet
korvaavatList = arcpy.ListFeatureClasses("","","Korvaavat") # korvaavat pisteet
lenkkiList = arcpy.ListFeatureClasses("","","Lenkkireitit") # analysoitujen lenkkireittien pisteet

# Yhdistetään kaikki listat
kaikki_pisteet = analyysiList + korvaavatList + lenkkiList

# Lisätään kaikkien pisteiden tiedot yhteen csv-tauluun
out_fp = r"[dir_fp]"
outfile = os.path.join(out_fp,"GPS_reitit_join.csv")

# Luupataan kaikki pisteet
for table in kaikki_pisteet:

    fields = arcpy.ListFields(table)                # listataan kentät
    field_names = [field.name for field in fields]  # tehdään kenttien nimistä lista
    iter_round = kaikki_pisteet.index(table)        # määritetään luupin iterointikierros
    with open(outfile,'ab') as f:                   # avataan csv-tiedosto 'append'-muodossa
            w = csv.writer(f)
            if iter_round == 0:                     # jos kyseessä ensimmäinen iterointikierros
                w.writerow(field_names)             # kirjoitetaan kenttien nimet
                for row in arcpy.SearchCursor(table):
                    field_vals = [row.getValue(field.name) for field in fields]
                    w.writerow(field_vals)
                del row
            else:                                   # muilla kierroksilla kenttien nimiä ei kirjoiteta
                for row in arcpy.SearchCursor(table):
                    field_vals = [row.getValue(field.name) for field in fields]
                    w.writerow(field_vals)
                del row


#  系统模块
from django.urls import path, include
from rest_framework import routers

# 自定义模块
from auto_test import views

router = routers.DefaultRouter()

router.register('users', views.UserViewSet)
router.register('groups', views.GroupViewSet)
# router.register('testapiview', views.test_apiview.as_view())

urlpatterns = [
     path('', include(router.urls)),
     path('test/', views.HelloWorld),
     path('testlist/', views.test_list),
     path('testapiview/', views.test_apiview),
]


from flask import Flask, render_template, request, redirect, url_for, flash
from flask_mysqldb import MySQL

app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'db_invoice'
mysql = MySQL(app)

app.secret_key = 'qwerty'

@app.route('/')
def Index():
    return render_template('index.html')

@app.route('/clientes')
def Clientes():
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM  customer')
    data = cur.fetchall()
    return render_template('clientes.html', customers = data)

@app.route('/facturar')
def facturar():
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM facturas')
    data = cur.fetchall()
    return render_template('facturar.html', invoices = data)

@app.route('/add', methods=['POST'])
def add_contact():
    if request.method == 'POST':
        id = request.form['id']
        name = request.form['name']
        status = request.form['status']
        mobile = request.form['mobile']
        cur = mysql.connection.cursor()
        cur.execute('INSERT INTO customer (id, name, status, mobile) VALUES (%s, %s, %s, %s)', (id,name, status, mobile))
        mysql.connection.commit()
        flash('Contacto Agregado de Forma Correcta')
        return redirect(url_for('Clientes'))

@app.route('/addfact', methods=['POST'])
def add_factura():
    if request.method == 'POST':
      date = request.form['date']
      id = request.form['idcli']
      price = request.form['price']
      balance = request.form['balance']
      cur = mysql.connection.cursor()
      cur.execute('INSERT INTO facturas (fecha, id_cli, price, balance) VALUES (%s, %s, %s, %s)', (date, id, price, balance))
      mysql.connection.commit()
      flash('Factura Agregada de Forma Correcta')
      return redirect(url_for('facturar'))

@app.route('/edit/<id>', methods = ['POST', 'GET'])
def editContact(id):
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM customer WHERE id = %s', [id])
    data = cur.fetchall()
    cur.close()
    return render_template('edit.html', customers = data[0])

@app.route('/editfact/<number>', methods = ['POST', 'GET'])
def editFactura(number):
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM facturas WHERE number = %s', [number])
    data2 = cur.fetchall()
    cur.close()
    return render_template('editfact.html', invoices = data2[0])

@app.route('/update/<id>', methods = ['POST', 'GET'])
def update(id):
    if request.method == 'POST':
        name = request.form['name']
        status = request.form['status']
        mobile = request.form['mobile']
        cur = mysql.connection.cursor()
        cur.execute("""
            UPDATE customer
            SET name = %s,
                status = %s,
                mobile = %s
            WHERE id = %s
        """, (name, status, mobile, id))
        mysql.connection.commit()
        flash('Cliente Actualizado')
        return redirect(url_for('Clientes'))

@app.route('/updatefact/<number>', methods = ['POST' , 'GET'])
def updatefact(number):
    if request.method == 'POST':
        #number = request.form['number']
        date = request.form['date']
        idcli = request.form['idcli']
        price = request.form['price']
        balance = request.form['balance']
        cur = mysql.connection.cursor()
        cur.execute("""
             UPDATE facturas
             SET fecha = %s,
                 id_cli = %s,
                 price = %s,
                 balance = %s
           WHERE number = %s
         """, (date, idcli, price, balance, number))
        mysql.connection.commit()
        flash('Factura Actualizada')
        return redirect(url_for('facturar'))

@app.route('/delete/<string:id>')
def delete_contact(id):
    cur = mysql.connection.cursor()
    cur.execute('DELETE FROM customer WHERE id = {0}'.format(id))
    mysql.connection.commit()
    flash('Contacto Removido Satisfactoriamente')
    return redirect(url_for('Clientes'))

@app.route('/deletefact/<string:number>')
def delete_factura(number):
    cur = mysql.connection.cursor()
    cur.execute('DELETE FROM facturas WHERE number = {0}'.format(number))
    mysql.connection.commit()
    flash('Factura Removida Satisfactoriamente')
    return redirect(url_for('facturar'))

if __name__ == '__main__':
    app.run(port = 3000, debug = True)


from app.classes.sql import Mysql

class UserBalance(Mysql):

    __BALANCE = "user_balance"

    def __init__(self):

        super().__init__()

    def user_balance(self, user_id):

        sql = f"Select * from {UserBalance.__BALANCE} where user_id = {user_id}"

        try:
            self.__amount = self.search(sql)

        except:

            raise Exception

        finally:

            self.close()

    @property
    def user_amount(self):

        return self.__amount[0]


"""
Integration test for replace_standard_id_in_domain_tables module

Original Issues: DC-808, DC-1170

The intent is to map the unmapped survey answers (value_as_concept_ids=0) using
value_source_concept_id through 'Maps to' relationship
"""

# Python Imports
import os

# Project Imports
from common import CONDITION_OCCURRENCE, CONCEPT, CONCEPT_RELATIONSHIP
from common import JINJA_ENV
from app_identity import PROJECT_ID
from cdr_cleaner.cleaning_rules.replace_standard_id_in_domain_tables import \
    ReplaceWithStandardConceptId, SRC_CONCEPT_ID_TABLE_NAME
from tests.integration_tests.data_steward.cdr_cleaner.cleaning_rules.bigquery_tests_base import \
    BaseTest

class ReplaceWithStandardConceptIdTest(BaseTest.CleaningRulesTestBase):

    @classmethod
    def setUpClass(cls):
        print('**************************************************************')
        print(cls.__name__)
        print('**************************************************************')

        super().initialize_class_vars()

        # Set the test project identifier
        cls.project_id = os.environ.get(PROJECT_ID)

        # Set the expected test datasets
        cls.dataset_id = os.environ.get('COMBINED_DATASET_ID')
        cls.sandbox_id = cls.dataset_id + '_sandbox'

        cls.rule_instance = ReplaceWithStandardConceptId(
            cls.project_id, cls.dataset_id, cls.sandbox_id)

        # Generates list of fully qualified table names and their corresponding sandbox table names
        for table_name in cls.rule_instance.affected_tables:
            cls.fq_table_names.append(
                f'{cls.project_id}.{cls.dataset_id}.{table_name}')
            cls.fq_table_names.append(
                f'{cls.project_id}.{cls.dataset_id}._mapping_{table_name}')
            sandbox_table_name = cls.rule_instance.sandbox_table_for(table_name)
            cls.fq_sandbox_table_names.append(
                f'{cls.project_id}.{cls.sandbox_id}.{sandbox_table_name}')

        cls.fq_table_names.extend([
            f'{cls.project_id}.{cls.dataset_id}.{table_name}'
            for table_name in [CONCEPT, CONCEPT_RELATIONSHIP]
        ])

        # Add _logging_standard_concept_id_replacement to fq_sandbox_table_names for cleanup in
        # teardown
        cls.fq_sandbox_table_names.append(
            f'{cls.project_id}.{cls.sandbox_id}.{SRC_CONCEPT_ID_TABLE_NAME}')

        # call super to set up the client, create datasets
        cls.up_class = super().setUpClass()

    def setUp(self):
        """
        Create empty tables for the rule to run on
        """
        # Create tables required for the test
        super().setUp()

        condition_occurrence_data_template = JINJA_ENV.from_string("""
        INSERT INTO `{{project_id}}.{{dataset_id}}.condition_occurrence` (
                condition_occurrence_id,
                person_id,
                condition_concept_id,
                condition_start_date,
                condition_start_datetime,
                condition_end_date,
                condition_end_datetime,
                condition_type_concept_id,
                stop_reason,
                provider_id,
                visit_occurrence_id,
                condition_source_value,
                condition_source_concept_id,
                condition_status_source_value,
                condition_status_concept_id)
        VALUES
              (1, 1, 319835, '2020-05-10', timestamp('2020-05-10 00:00:00 UTC'), null, null, 0, null, null, null, null, 45567179, null, null),
               (2, 1, 0, '2020-05-10', timestamp('2020-05-10 00:00:00 UTC'), null, null, 0, null, null, null, null, 45567179, null, null),
               (3, 1, 45567179, '2020-05-10', timestamp('2020-05-10 00:00:00 UTC'), null, null, 0, null, null, null, null, 0, null, null),
               (4, 1, 45567179, '2020-05-10', timestamp('2020-05-10 00:00:00 UTC'), null, null, 0, null, null, null, null, 45567179, null, null),
               (5, 1, 40398862, '2020-05-10', timestamp('2020-05-10 00:00:00 UTC'), null, null, 0, null, null, null, null, 40398862, null, null),
               (6, 1, 45587397, '2020-05-10', timestamp('2020-05-10 00:00:00 UTC'), null, null, 0, null, null, null, null, 45587397, null, null)
        """)

        mapping_condition_occurrence_data_template = JINJA_ENV.from_string("""
        INSERT INTO `{{project_id}}.{{dataset_id}}._mapping_condition_occurrence`
        (
          condition_occurrence_id, src_table_id, src_dataset_id, src_condition_occurrence_id, src_hpo_id)
        VALUES
               (1, 'hpo_condition_occurrence', 'hpo_dataset', 10, 'test_hpo'),
               (2, 'hpo_condition_occurrence', 'hpo_dataset', 20, 'test_hpo'),
               (3, 'hpo_condition_occurrence', 'hpo_dataset', 30, 'test_hpo'),
               (4, 'hpo_condition_occurrence', 'hpo_dataset', 40, 'test_hpo'),
               (5, 'hpo_condition_occurrence', 'hpo_dataset', 50, 'test_hpo'),
               (6, 'hpo_condition_occurrence', 'hpo_dataset', 60, 'test_hpo')
        """)

        concept_data_template = JINJA_ENV.from_string("""
        INSERT INTO `{{project_id}}.{{dataset_id}}.concept`
        (
          concept_id, concept_name, standard_concept, domain_id, vocabulary_id, concept_class_id, concept_code, valid_start_date, valid_end_date)
        VALUES
               (319835, 'Congested Heart Failure', 'S', 'foo', 'bar', 'baz', 'alpha', '2020-01-01', '2099-12-31'),
               (45567179, 'Congested Heart Failure', 'C', 'foo', 'bar', 'baz', 'beta', '2020-01-01', '2099-12-31'),
               (45587397, 'Anaemia complicating pregnancy, childbirth and the puerperium', 'C', 'foo', 'bar', 'baz', 'gamma', '2020-01-01', '2099-12-31'),
               (434701, 'Anemia in mother complicating pregnancy, childbirth AND/OR puerperium', 'S', 'foo', 'bar', 'baz', 'rho', '2020-01-01', '2099-12-31'),
               (444094, 'Finding related to pregnancy', 'S', 'foo', 'bar', 'baz', 'phi', '2020-01-01', '2099-12-31'),
               (40398862, 'Ischemic chest pain', 'C', 'foo', 'bar', 'baz', 'zed', '2020-01-01', '2099-12-31')
        """)

        concept_relationship_data_template = JINJA_ENV.from_string("""
        INSERT INTO `{{project_id}}.{{dataset_id}}.concept_relationship`
        (
          concept_id_1, concept_id_2, relationship_id, valid_start_date, valid_end_date)
        VALUES
               (319835, 319835, 'Maps to', '2020-01-01', '2099-12-31'),
               (45567179, 319835, 'Maps to', '2020-01-01', '2099-12-31'),
               (45587397, 434701, 'Maps to', '2020-01-01', '2099-12-31'),
               (45587397, 444094, 'Maps to', '2020-01-01', '2099-12-31')
        """)

        concept_data_query = concept_data_template.render(
            project_id=self.project_id, dataset_id=self.dataset_id)

        concept_relationship_data_query = concept_relationship_data_template.render(
            project_id=self.project_id, dataset_id=self.dataset_id)

        condition_occurrence_data_query = condition_occurrence_data_template.render(
            project_id=self.project_id, dataset_id=self.dataset_id)

        mapping_condition_occurrence_data_query = mapping_condition_occurrence_data_template.render(
            project_id=self.project_id, dataset_id=self.dataset_id)

        # Load test data
        self.load_test_data([
            f'''{concept_data_query};
                {concept_relationship_data_query};
                {condition_occurrence_data_query};
                {mapping_condition_occurrence_data_query}'''
        ])

    def test_replace_standard_id_in_domain_tables(self):
        """
        condition_occurrence

        record 1: condition_concept_id is already standard, so do nothing

        record 2: condition_concept_id is 0, but condition_source_concept_id 45567179 can be
        mapped to the standard concept 319835. So condition_concept_id should be replaced with
        319835 and this record is sandboxed.

        record 3: condition_concept_id is the non-standard 45567179 and
        condition_source_concept_id 0. 45567179 can be mapped to the standard concept 319835. So
        condition_concept_id should be replaced with 319835 and condition_source_concept_id
        should be replaced by the original condition_concept_id 45567179 and this record is
        sandboxed.

        record 4: condition_concept_id is the non-standard 45567179 and
        condition_source_concept_id the same non-standard 45567179. 45567179 can be mapped to the
        standard concept 319835. So condition_concept_id should be replaced with 319835 and
        condition_source_concept_id remains the same and this record is sandboxed.

        record 5: condition_concept_id is the non-standard 40398862 and
        condition_source_concept_id the same non-standard 40398862, but there is no standard
        concept mapping for 40398862. Although condition_concept_id and
        condition_source_concept_id remain the same, this record is still sandboxe because this
        record is flagged as being non-standard.

        record 6: condition_concept_id is the non-standard 45587397 and
        condition_source_concept_id the same non-standard 45587397. 45567179 can be mapped to two
        standard concepts 434701 and 444094. So this record is split into two new records,
        the new ids are generated using this logic MAX(condition_occurrence_id) + ROW_NUMBER().
        Two new records with condition_occurrence_id 7 and 8 are generated and the corresponding
        mapping table _mapping_condition_occurrence is updated as well. This record is sandboxed.

        :return:
        """
        # Expected results list
        tables_and_counts = [{
            'fq_table_name':
                f'{self.project_id}.{self.dataset_id}.{CONDITION_OCCURRENCE}',
            'fq_sandbox_table_name':
                f'{self.project_id}.{self.sandbox_id}.{self.rule_instance.sandbox_table_for(CONDITION_OCCURRENCE)}',
            'loaded_ids': [1, 2, 3, 4, 5, 6],
            'sandboxed_ids': [2, 3, 4, 5, 6],
            'fields': [
                'condition_occurrence_id', 'person_id', 'condition_concept_id',
                'condition_source_concept_id'
            ],
            'cleaned_values': [
                (1, 1, 319835, 45567179), (2, 1, 319835, 45567179),
                (3, 1, 319835, 45567179), (4, 1, 319835, 45567179),
                (5, 1, 40398862, 40398862), (7, 1, 434701, 45587397),
                (8, 1, 444094, 45587397)
            ]
        }, {
            'fq_table_name':
                f'{self.project_id}.{self.dataset_id}._mapping_{CONDITION_OCCURRENCE}',
            'loaded_ids': [1, 2, 3, 4, 5, 6],
            'fields': [
                'condition_occurrence_id', 'src_condition_occurrence_id'
            ],
            'cleaned_values': [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50),
                               (7, 60), (8, 60)]
        }]

        self.default_test(tables_and_counts)


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 23:37:30 2023

@author: Aryaman Kumar
"""
n=int(input())
list1=[]
list2=[]
dict1={}
for i in range(n):
    a=int(input())
    list1.append(a)

for i in range(n):
    list2.append(list1.count(list1[i]))
    dict1[list2[i]]=list1[i]
set1=set(sorted(list2))
list3=list(set1)
print(list2)
print("Highest frequency",dict1[list3[len(list3)-1]])
print("second highest",dict1[list3[len(list3)-2]])


import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class ProfessorTests(unittest.TestCase):

    def setUp(self):
        # Initialize the WebDriver (e.g., for Chrome)
        self.driver = webdriver.Chrome(executable_path='C://programming//chromedriver_win32//chromedriver.exe')

    def tearDown(self):
        # Close the WebDriver after each test
        self.driver.quit()

    def test_add_professor(self):
        driver = self.driver
        driver.get("http://localhost/WebProgramming")  # Replace with your website URL

        # Locate and click the "Add Professor" button
        add_professor_button = driver.find_element(By.ID, "addProfessorButton")
        add_professor_button.click()

        # Wait for the modal to appear (you may need to adjust the wait time)
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "addProfessorModal"))
        )

        # Locate the input fields in the modal
        fullname_input = driver.find_element(By.NAME, "fullname")
        email_input = driver.find_element(By.NAME, "email")
        phone_input = driver.find_element(By.NAME, "phone")
        gender_select = driver.find_element(By.NAME, "gender")
        dob_input = driver.find_element(By.NAME, "dateofbirth")

        # Enter professor information
        fullname_input.send_keys("John Doe")
        email_input.send_keys("johndoe@example.com")
        phone_input.send_keys("1234567890")
        gender_select.select_by_value("male")  # Replace with the appropriate value
        dob_input.send_keys("2000-01-01")  # Replace with the appropriate date

        # Locate and click the "Submit" button in the modal
        submit_button = driver.find_element(By.XPATH, "//button[text()='Submit']")
        submit_button.click()

        # Wait for the modal to close (you may need to adjust the wait time)
        WebDriverWait(driver, 10).until(
            EC.invisibility_of_element_located((By.ID, "addProfessorModal"))
        )

        # Verify that the new professor is displayed on the page
        new_professor = driver.find_element(By.XPATH, "//h5[text()='John Doe']")
        self.assertEqual(new_professor.text, "John Doe")

    # Add more test cases for other professor-related functionalities (e.g., editing, deleting, viewing profile, etc.)

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


from sortedcontainers import SortedList
class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        l = SortedList()
        res = [0]*len(nums)
        for i in range(len(nums)-1,-1,-1):
            value = nums[i]
            bi = l.bisect_left(value)
            res[i] = bi
            l.add(value)
        return res


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

from PKC_Classes import NetworkUser, KDC
from DES import DES
from RSA_Class import RSA

import socket
import os
import sys
import time

if sys.version_info[0] < 3:
    raise Exception("Must be using Python 3")

alice = NetworkUser('Alice', DES(), RSA(9973, 97), 100)
print('alice:', alice.uid)
# socket communication
kdc_host, kdc_port = 'localhost', 9999
bob_host, bob_port = 'localhost', 9200
bob_uid = 200
# talk to kdc for sess key
try:
    sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_with_kdc.connect((kdc_host, kdc_port))
    print(sock_with_kdc.recv(1024))
    # send cipher_key
    alice_cipher_key_packet = alice.send_cipher_key()
    sock_with_kdc.send(alice_cipher_key_packet.encode())

    kdc_alice_cipher_key_packet = sock_with_kdc.recv(1024).decode()
    print(kdc_alice_cipher_key_packet)
    alice.process_packet(kdc_alice_cipher_key_packet)

    # ask for bob's sess key
    print('ask for the sess key to talk to ', bob_uid)
    packet_REQ_KEY = alice.request_key(bob_uid)
    sock_with_kdc.send(packet_REQ_KEY.encode())
    packet_RPY_KEY = sock_with_kdc.recv(1024).decode()

    print(packet_RPY_KEY)
except socket.error as msg:
    print(msg);
    sys.exit(1)

# sock_with_kdc.shutdown(socket.SHUT_WR)

# talk to bob
try:
    sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_self.connect((bob_host, bob_port))
    print('connecting to bob')
    # talk to bob
    packet_REQ_CON = alice.request_connection(packet_RPY_KEY)
    sock_self.send(packet_REQ_CON.encode())
    packet_RPY_CHLNG = sock_self.recv(1024).decode()

    packet_RPY_CHLNG_SOL = alice.reply_challenge_sol(packet_RPY_CHLNG, bob_uid)
    sock_self.send(packet_RPY_CHLNG_SOL.encode())
    connection_rst = sock_self.recv(1024).decode()
    if connection_rst == '1':
        print('session created successfully!')
    else:
        print('session created failed!')
    print('finish task')
except socket.error as msg:
    print(msg);
    sys.exit(1)

sock_with_kdc.shutdown(socket.SHUT_WR)
sock_self.shutdown(socket.SHUT_WR)
sock_with_kdc.close()
sock_self.close()


class Solution(object):
    def numOfSubarrays(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        # This is an elementary dynamic programming problem.
        # odd[i] records the number of subarray ending at arr[i] that has odd sum.
        # even[i] records the number of subarray ending at arr[i] that has even sum.
        # if arr[i + 1] is odd, odd[i + 1] = even[i] + 1 and even[i + 1] = odd[i]
        # if arr[i + 1] is even, odd[i + 1] = odd[i] and even[i + 1] = even[i] + 1

        res = odd = even = 0
        for a in arr:
            even += 1 # why not odd += 1? Cause the first sum is 0, so even should lead
            if a % 2:
                # flip count if only we see an odd
                odd, even = even, odd
            res = (res + odd) % (10**9 + 7)
        return res


from app.config.db import db
from orator import Model, SoftDeletes

Model.set_connection_resolver(db)

class Penyakit(SoftDeletes,Model):
    __table__   = 'penyakit'
    __guarded__ = ['id']
    __dates__ = ['deleted_at']

    def store(request):
        input_data = Penyakit()
        input_data.kode_penyakit = request['kode_penyakit']
        input_data.nama_penyakit = request['nama_penyakit']
        input_data.penyebab      = request['penyebab']
        input_data.solusi        = request['solusi']
        input_data.save()
        return True


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('results/', views.results, name='results'),
    path('sendmail/', views.sendmail, name='sendmail'),
    path('addcontact/', views.addcontact, name='addcontact'),
    path('ajaxForm/', views.ajaxForm, name='ajaxForm')
]